Calling a windows form from another thread (.Net)

后端 未结 2 1266
迷失自我
迷失自我 2020-12-19 11:22

Hi I\'m developing a .Net application and I want to achieve the following:

I have a winforms application, and a timer (System.Timers.timer) that excecutes a thread b

相关标签:
2条回答
  • 2020-12-19 12:05

    Let's say that your worker method (that you execute in a thread) is

    DoWork(args)
    {
        ...
        UpdateUI();
    }
    

    The method that handles timer's Elapsed event should do this:

    OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
        args = GetArgs();
        this.BeginInvoke(() => DoWork(args));
        // 'this' refers to form here.
        // You can also use BeginInvoke on a user control for updating it.
    }
    

    This will run DoWork in a seperate thread and DoWork will have the ability of updating UI.

    0 讨论(0)
  • 2020-12-19 12:21
     formObject.Invoke(delegate { 
          // action to perform on UI thread
     });
    
    0 讨论(0)
提交回复
热议问题