2013-04-29 68 views
0

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

我该如何获得所有同时运行的任务,并在主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是一个列表框。当我运行这个代码时,怎么会发现id没有看到添加到这个listbox的最小素数? (3,5,7,11等)。

回答

2

使用调度到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!"; })); 
}); 
+0

感谢您的帮助。我该如何处理任务? – 2013-04-30 14:31:14

+0

我已经更新了示例代码,使用Task.Run()。 – IsNull 2013-04-30 14:39:20

+0

请看我的新问题,我写了一些代码,但它不像我想要的那样行事。 – 2013-04-30 17:50:24

相关问题