Why can I access controls from a form in a thread without cross thread exception?

前端 未结 3 1891
旧巷少年郎
旧巷少年郎 2020-12-22 08:52

Usually, when you access controls in a Thread you end up with some cross thread exceptions. In my C# WinForms Application I have a picture box and a toolstriplabel which do

相关标签:
3条回答
  • 2020-12-22 09:08

    You won't get cross thread exception, but it doesn't mean that this is a safe operation. There is always a possibility for your control to go unstable. You just don't know when it will happen.

    See the following explanation from Microsoft. http://msdn.microsoft.com/en-us/library/ms171728.aspx

    Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible, such as race conditions and deadlocks. It is important to make sure that access to your controls is performed in a thread-safe way.

    0 讨论(0)
  • 2020-12-22 09:13

    You don't necessarily always have to call BeginInvoke/Invoke. Sometimes the operation is running on the foreground thread, sometimes it is in the background.

    Per the microsoft samples that are everywhere, You can SHOULD check to see if calling BeginInvoke/Invoke is required.

    private void SetTextStandardPattern()
    {
        if (this.InvokeRequired)
        {
            this.Invoke(SetTextStandardPattern);
            return;
        }
        this.text = "New Text";
    }
    

    Here is a nice microsoft article that has a sample: http://msdn.microsoft.com/en-us/library/ms171728(v=vs.80).aspx

    and here is another article on how to "avoid" the pattern: http://www.codeproject.com/Articles/37642/Avoiding-InvokeRequired

    0 讨论(0)
  • 2020-12-22 09:21

    I have these three possibilites in mind:

    1. The action is already dispatched to the gui thread.
    2. The action doesn't need to be dispatched currently.
    3. The action is somehow executed from the gui thread.

    It's most likely number 3.

    0 讨论(0)
提交回复
热议问题