What is considered good programming practice in multi-threaded winform applications using delegates?

I am modifying an application written in C # that makes heavy use of multithreading to play audio files and display images for the user. Given that it is multithreaded, I often need to use the Invoke method to change form elements. I come across a template that I’m not comfortable with, where I find that I write frequent, small, delegated methods that usually do only one thing. An example of this is the following:

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");
    }
    ...
}

, , ? , , , "" .

.

+5
3

. Action - , :

private void SomeOtherMethod()
{
    Action action = () => pictureBox1.Image = Image.FromFile("example.png");
    if (pictureBox1.InvokeRequired)
    {
        Invoke(action);
    }
    else
    {
        action();
    }
}

if InvokeRequired , :

public static void InvokeIfRequired(Control control, Action action)
{
    if (control.InvokeRequired)
    {
        control.Invoke(action);
    }
    else
    {
        action();
    }
}

private void SomeOtherMethod()
{
    InvokeIfRequired(() => pictureBox1.Image = Image.FromFile("example.png");
}
+6

.

this.BeginInvoke( (Action) (()=>
    {
        pictureBox1.Image = Image.FromFile("example.png");
    }));
+8

MethodInvoker -. , - :

void SomeMethod(/* with whatever args */) {
    if (InvokeRequired)
        Invoke(new MethodInvoker(() => SomeMethod(/* args used to call method */)));
    else
        // the method body itself
}
+1

All Articles