C # problem using delegates for cross-threading

I have a problem using delegates to change Textboxfrom a thread that is not the main form thread.

I have two classes: the main class Form1.cs with the UI and another class LINClass.cs, where I wrote the device functions. In Form1, I run a background executor that constantly polls the device, and another stream that retrieves data from the device (RXTask ()), all the functions of these two streams are associated with LINCLass.cs.

The stream that retrieves data from the device contains a delegate that points to the Form1.cs function, which allows you to change the text fields of Form1:

public class LINClass : Form
{
    private delegate void FormUpdater(int devnum, string rpm, string current, string temp);

//some other variables and procedure

public void RXTask()
{
    FormUpdater frmUpdt = new FormUpdater(Form1.GUIupdate);
    //other procedures and a loop containing the invoke...
    this.Invoke(frmUpdt, new object[]{devnum, rpm,
                                        current,
                                        temperature});

}

The class Form1 contains the called method written below

public static void GUIupdate(int eWPnum, string rpm, string current, string temp)
{
    //take the parameters and write them in the textbox
}

, , , .

http://s13.postimg.org/9ohuj9d7r/exception.png

: "InvalidOperationException , Invoke BeginInvoke , "

+4
2

, .

+1

this.Invoke(), .

- OnLoad() :

private bool isLoaded;

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    Volatile.Write(ref isLoaded, true);
}

:

public void RXTask()
{
    FormUpdater frmUpdt = new FormUpdater(Form1.GUIupdate);
    //other procedures and a loop containing the invoke...

    if (Volatile.Read(ref isLoaded))
    {
        this.Invoke(frmUpdt, new object[]
        {
            devnum, rpm,
            current,
            temperature
        });
    }
}

( .NET Volatile.Read()/Volatile.Write(), volatile.)

+1

Source: https://habr.com/ru/post/1626535/


All Articles