如何使某些任务更改我的WPF控件 [英] How to make some Tasks change my WPF controls

查看:137
本文介绍了如何使某些任务更改我的WPF控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

(13/04/13:)

(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看不到添加到此列表框中的最小素数? (3,5,7,11依此类推).

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).

推荐答案

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

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!"; }));
});

这篇关于如何使某些任务更改我的WPF控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆