How to make some Tasks change my WPF controls

你。 提交于 2019-12-11 20:37:36

问题


I want to create a WPF application that does this: The application will have 8 Tasks running together. Each task will be able to ad some strings to a text box shown in the main window.

how do I get the tasks all running at the same time, and running on the main UI Thread?

(30/04/13:)

please see the next code:

private  void RunTasks(int ThreadsNumber)
    {           

        int Ratio = NumbersToCheck / ThreadsNumber;

        for (int i = 0; i < ThreadsNumber; i++)
        {
            Task.Run(() =>
                {
                    int counter = 0;
                    int low = Ratio * i;
                    int high = Ratio * (i + 1);

                    Dispatcher.Invoke(DispatcherPriority.Normal,
                                      (Action)(() =>
                                      {
                                          for (int j = low; j < high; j++)
                                          {
                                              if(IsPrime(j))
                                                  MessageList.Items.Add(j);

                                          }
                                      }));
                });                
        }

    }

MessageList is a listbox. how come when I run this code, id don't see the smallest prime numbers added to this listbox? (3,5,7,11 and so on).


回答1:


Use the Dispatcher to invoke code on the UI thread from your async running one:

// The Work to perform on another thread
Task.Run(()=>
{
  // long running operation...


  // Sets the Text on a Text Control from the Dispatcher 
  // so it will access the UI from the UI-Thread
  Dispatcher.Invoke(DispatcherPriority.Normal, 
                    (Action)(() => { myText.Text = "From other thread!"; }));
});


来源:https://stackoverflow.com/questions/16287010/how-to-make-some-tasks-change-my-wpf-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!