【问题标题】:How to Call a method in UI thread from another running thread in UWP? [duplicate]如何从 UWP 中另一个正在运行的线程调用 UI 线程中的方法? [复制]
【发布时间】:2017-12-21 02:47:55
【问题描述】:

我想从线程内部调用Update(int i)。我曾经使用BeginInvoke(),但在UWP中不可用。

public class Viewmodel
{
 Viewmodel()
 {
   //start task
   var mainTask = Task.Factory.StartNew(() =>
   {
     MyThread();
   });
 }
 private void MyThread()
 {
    int i;
    while(condition)
    {
      //do somethings
      Update(i) 
    }
 }
 private Update(int i)
 {
   //do somethings
 }
}

【问题讨论】:

    标签: c# multithreading uwp task


    【解决方案1】:

    以下应该可以工作。

    Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
    () =>
    {
        // update your UI here
        Update(i) 
    });
    

    【讨论】:

    • 由于原始问题提到在视图模型类中运行,您可以改用this.Dispatcher。如果应用程序有多个视图,则依赖 MainView 会导致中断。
    • 当我想调用 Update() 时,我会在 Task 内部哪里使用此代码?
    • @AmirHusseinNargesian 你可以把它放在 Update() 函数中,然后在 Dispatch 处理程序中添加你的逻辑。
    【解决方案2】:

    您可以使用以下代码来运行您的代码:

    await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.High/* the rank */,
    () =>
    {
        // run the code
    });
    

    我还有其他方法可以做到这一点

      await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal /*the rank*/, () => { // run the code  });
    

    https://stackoverflow.com/a/38175976/6116637

    【讨论】:

    • The documentation 明确表示不要使用值High
    • @PeterTorr-MSFT Thx,但我想说您可以在此设置排名。
    猜你喜欢
    • 2012-04-27
    • 1970-01-01
    • 2012-01-24
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2012-07-01
    相关资源
    最近更新 更多