【发布时间】:2016-01-07 00:14:42
【问题描述】:
请参考我下面的代码。
public MainViewModel()
{
LongRunningOperationCommand = new RelayCommand(ExecuteLongRunningOperationCommand);
}
private void ExecuteLongRunningOperationCommand()
{
Test();
}
private async Task Test()
{
Log += "Command begin: " + DateTime.Now + "\r\n";
Log += "Command thread: " + Thread.CurrentThread.ManagedThreadId + "\r\n";
var getStringAsync = GetStringAsync();
Log += "Work in Command...\r\n";
Log += "Work in Command which not related to the result of async method will complete: " + DateTime.Now + "\r\n";
Log += "Work in Command which not related to the result of async method will complete, thread: " +
Thread.CurrentThread.ManagedThreadId + "\r\n";
string result = await getStringAsync;
Log += "Command will complete: " + DateTime.Now + "\r\n";
Log += "Command will complete, thread: " + Thread.CurrentThread.ManagedThreadId + "\r\n";
Log += result + "\r\n";
}
private async Task<string> GetStringAsync()
{
Log += "Async method begin: " + DateTime.Now + "\r\n";
Log += "Async method thread: " + Thread.CurrentThread.ManagedThreadId + "\r\n";
Log += "Work in Async method... \r\n";
await Task.Delay(10000);
Log += "Async method will complete: " + DateTime.Now + "\r\n";
Log += "Async method will complete, thread: " + Thread.CurrentThread.ManagedThreadId + "\r\n";
return "GetStringAsync method completed!";
}
结果如下
Command begin: 1/6/2016 11:58:37 PM
Command thread: 8
Async method begin: 1/6/2016 11:58:37 PM
Async method thread: 8
Work in Async method...
Work in Command...
Work in Command which not related to the result of async method will complete: 1/6/2016 11:58:37 PM
Work in Command which not related to the result of async method will complete, thread: 8
Async method will complete: 1/6/2016 11:58:47 PM
Async method will complete, thread: 8
Command will complete: 1/6/2016 11:58:47 PM
Command will complete, thread: 8
GetStringAsync method completed!
GetStringAsync 方法中 await Task.Delay 之后的线程 id 应该与之前不同。为什么结果是一样的?在控制台应用程序中,线程 ID 不同,但在 WPF 应用程序中,它们是相同的。有人可以帮忙吗?
【问题讨论】:
-
+=不是线程安全的,如果多个线程同时尝试更新字符串(例如在您的控制台版本中),您可能会丢失日志消息。
标签: c# wpf multithreading asynchronous async-await