C# Multithreading — Invoke without a Control

前端 未结 7 1163
闹比i
闹比i 2020-12-13 20:44

I am only somewhat familiar with multi-threading in that I\'ve read about it but have never used it in practice.

I have a project that uses a third party library tha

7条回答
  •  时光取名叫无心
    2020-12-13 21:28

    The handling method could simply store the data into a member variable of the class. The only issue with cross-threading occurs when you want to update threads to controls not created in that thread context. So, your generic class could listen to the event, and then invoke the actual control you want to update with a delegate function.

    Again, only the UI controls that you want to update need to be invoked to make them thread safe. A while ago I wrote a blog entry on a "Simple Solution to Illegal Cross-thread Calls in C#"

    The post goes into more detail, but the crux of a very simple (but limited) approach is by using an anonymous delegate function on the UI control you want to update:

    if (label1.InvokeRequired) {
      label1.Invoke(
        new ThreadStart(delegate {
          label1.Text = "some text changed from some thread";
        }));
    } else {
      label1.Text = "some text changed from the form's thread";
    }
    

    I hope this helps. The InvokeRequired is technically optional, but Invoking controls is quite costly, so that check ensure it doesn't update label1.Text through the invoke if its not needed.

提交回复
热议问题