2015-06-16 29 views
1

我使用WPF 4.5和MVVM卡利Micro和具有以下WPF代码:以上WPF 4.5:如何创建子线程并继续任务到UI主线程?

public class MainViewModel: Screen 
{ 
    public MainViewModel() 
    { 
     if (!ConnectServer()) 
     { 
      Console.WriteLine("Connection failed"); 
      return; 
     } 
     // Following method can only be run if server connection established 
     ProcessThis(); 
    } 
} 

我的代码只有一次机会来连接,如果失败则显示视图,什么也不做。如果我使用while(!ConnectServer()),它将一直阻塞UI线程,这意味着连接仍然失败时,用户不会显示任何内容。这非常难看。

我想要什么:

  1. 如果连接失败,意味着ConnectServer的()返回false,应等待10秒钟,然后尝试重新连接,并再次(如调用一个方法RetryConnect())。直到它成功而不会阻塞 UI线程。
  2. 连接后,它应该继续到主线程并运行ProcessThis()。

理论上我知道它需要背景分离的线程,但我不知道如何实现它简单和良好。请随意使用我的示例代码来解释。先谢谢你。

+0

这是异步/ AWAIT是什么https://msdn.microsoft.com/en-us/library/hh191443.aspx –

+0

['DispatcherTimer'](https://msdn.microsoft.com/ en-us/library/system.windows.threading.dispatchertimer(v = vs.110).aspx)fits。 – Sinatr

回答

3

要启动后台任务,您可以使用Task.Run方法。 而在主线程可以使用页面调度执行代码(VM上下文的情况下,我已经把Application.Current.Dispatcher的调用)

public class MainViewModel: Screen 
{ 
    public MainViewModel() 
    { 
     Task.Run(() => 
     { 
      while (!ConnectServer()) 
      { 
       Console.WriteLine("Connection failed"); 
       Thread.Sleep(10*1000); 
      } 

      // Following method can only be run if server connection established 
      Application.Current.Dispatcher.Invoke(ProcessThis); 
     } 
    } 
} 

而不是使用调度的,你可以利用新的异步/等待功能来实现它。

public class MainViewModel: Screen 
{ 
    public MainViewModel() 
    { 
     Initialize(); 
    } 
} 

private async void Initialize() 
{ 
     await Task.Run(async() => 
     { 
      while (!ConnectServer()) 
      { 
       Console.WriteLine("Connection failed"); 
       await Task.Delay(10*1000); 
      } 
     } 

     // Following method can only be run if server connection established 
     ProcessThis(); 
} 
+0

非常明确的解释!非常感谢你。 – MagB

相关问题