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

前端 未结 3 1898
旧巷少年郎
旧巷少年郎 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: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

提交回复
热议问题