Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is considered good programming practice in multi-threaded winform applications with delegate usage?

I'm modifying an application written in C# that makes heavy-use of multi-threading to play audio files and display images to a user. Given that it is multi-threaded, I need to use the Invoke method often to change form elements. I'm running into a pattern that I'm not very comfortable with, where I find myself writing frequent, small, delegate methods that typically only do one thing. An example of this is as follows:

delegate void setImageCallback(Image img);
private void setImage(Image img)
{
    this.pictureBox1.Image = img;
}

private void someOtherMethod()
{
    ...
    if (this.pictureBox1.InvokeRequired)
    {
        this.Invoke(new setImageCallback(setImage), Image.FromFile("example.png");
    }
    else
    {
        this.pictureBox1.Image = Image.FromFile("example.png");
    }
    ...
}

How do people generally handle these situations, so that you don't find yourself writing an absurd number of delegates and methods just to remain thread-safe? Obviously, consolidation of similar methods is great, but if I potentially need to update every form element on my form, I don't want to have a "modify" delegate and method for each of these.

Thanks.

like image 358
rybosome Avatar asked May 30 '11 01:05

rybosome


1 Answers

A good example is here.

this.BeginInvoke( (Action) (()=>
    {
        pictureBox1.Image = Image.FromFile("example.png");
    }));
like image 81
Jason Down Avatar answered Nov 03 '22 00:11

Jason Down