【问题标题】:How to make some Tasks change my WPF controls如何使某些任务更改我的 WPF 控件
【发布时间】:2013-04-29 19:49:20
【问题描述】:

我想创建一个 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 等)。

【问题讨论】:

    标签: wpf multithreading task ui-thread


    【解决方案1】:

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

    【讨论】:

    • 感谢您的帮助。我该如何处理任务?
    • 请看我的新问题,我写了一些代码,但它的行为不像我想要的那样。
    猜你喜欢
    • 1970-01-01
    • 2021-07-04
    • 2011-06-30
    • 2014-06-04
    • 2011-09-08
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多