WPF 4.5:如何创建子线程并将任务继续到 UI 主线程?
WPF 4.5: How to create child thread and continue task to UI main thread?
我使用 WPF 4.5 和 MVVM Caliburn Micro 并具有以下 WPF 代码:
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 线程,这意味着当连接仍然存在时不会向用户显示任何内容 failed.It 非常难看。
我想要的:
- 如果连接失败,意味着 ConnectServer() returns false,它应该等待 10 秒并一次又一次地尝试连接(例如调用方法 RetryConnect())直到成功 没有阻塞 UI 线程。
- 和连接后,应该继续主线程和运行 ProcessThis().
理论上我知道它需要后台线程分离,但我不知道如何简单好地实现它。请随意使用我的示例代码来解释。提前谢谢你。
要启动后台任务,您可以使用 Task.Run 方法。
要在主线程中执行代码,您可以使用页面的 Dispatcher(如果是 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);
}
}
}
您可以利用新的 async/await 功能来实现它,而不是使用 Dispatcher。
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();
}
我使用 WPF 4.5 和 MVVM Caliburn Micro 并具有以下 WPF 代码:
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 线程,这意味着当连接仍然存在时不会向用户显示任何内容 failed.It 非常难看。
我想要的:
- 如果连接失败,意味着 ConnectServer() returns false,它应该等待 10 秒并一次又一次地尝试连接(例如调用方法 RetryConnect())直到成功 没有阻塞 UI 线程。
- 和连接后,应该继续主线程和运行 ProcessThis().
理论上我知道它需要后台线程分离,但我不知道如何简单好地实现它。请随意使用我的示例代码来解释。提前谢谢你。
要启动后台任务,您可以使用 Task.Run 方法。 要在主线程中执行代码,您可以使用页面的 Dispatcher(如果是 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);
}
}
}
您可以利用新的 async/await 功能来实现它,而不是使用 Dispatcher。
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();
}