How to debug Cross-Thread exceptions in .NET?

I tested the program I am writing and received this error message: Cross-thread operation not valid: Control 'lblStatus' accessed from a thread other than the thread it was created on

The code is a bit massive, and I'm not sure which part is causing this error to accommodate a smaller segment. However, there is information that may be helpful.

I do not use any "threads" explicitly. I assume that something else automatically creates multiple threads - I use the Wii remote hardware access library, and I do the graphics.

The stack trace indicates that the call is made by the on change event handler, which calls the function within which it is lblStatustrying to be changed, but not executed.

I was wondering how you are debugging these types of errors. I am using Visual Studio 2008.

EDIT

One thing I want to clarify, I do not know how this other thread even came. How can I find this? source of another thread.

+3
source share
4 answers
public void SetStatus(string msg)
{
    if (lblStatus.InvokeRequired)
        lblStatus.Invoke(new MethodInvoker(delegate
        {
            lblStatus.Text = msg;
        }));
    else
        lblStatus.Text = msg;
}

This will update the text of your label.

For BeginInvoke, this is what I know (I know there are more elegant implementations) - but I have not tried this in a multi-threaded application yet:

Action<string> setStatus= target.AppendText;

void OnSomeEvent (object sender, EventArgs e)
{ 
    IAsyncRes iares = setStatus.BeginInvoke("status message", null, null); 
    setStatus.EndInvoke(iares);
}

public void SetStatus(string msg)
{ lblStatus.Text = msg; }

For various synchronization methods with the control flow, SnOrfus refers to an excellent link. My example above on BeginInvoke is incorrect for synchronizing with the control flow.

As for the thread: About the WiimoteChanged event

+4
source

, . Dispatcher.Invoke() , .

:

this.Dispatcher.Invoke((Action)(() => lblStatus.Content = "Hello"));

( ):

this.Dispatcher.Invoke((Action)delegate() { lblStatus.Content = "Hello"; });
+2

.

, .

0

, , ,

, Visual Studio. Visual Studio , , . , Form.ActiveForm Application.Run.

If this is your problem, you can uncheck the Enable Visual Studio Hosting checkbox on the Debug tab of the project properties.

0
source

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


All Articles