请参阅我的代码如下。为什么呼叫方法和异步方法具有相同的线程ID
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!
线程ID在GetStringAsync后等待Task.Delay方法应该与之前不同。为什么结果是一样的?在控制台应用程序中,线程ID不同,但在WPF应用程序中,它们是相同的。任何人都可以帮忙
'+ ='不是线程安全的,如果多个线程尝试同时更新字符串(如在控制台版本中),则可能会丢失日志消息。 –