1

我想创建一个执行此操作的 WPF 应用程序:该应用程序将有 8 个任务一起运行。每个任务都可以将一些字符串添加到主窗口中显示的文本框中。

如何让所有任务同时运行,并在主 UI 线程上运行?

(30/04/13:)

请看下面的代码:

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 是一个列表框。为什么当我运行这段代码时,我没有看到添加到这个列表框中的最小素数?(3、5、7、11 等)。

4

1 回答 1

3

使用Dispatcher从您的异步运行线程调用 UI 线程上的代码:

// 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!"; }));
});
于 2013-04-29T22:02:24.003 回答