话不多说,直接先贴代码。
控制台程序:
using System;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApp7
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Main方法的线程ID是:" + Thread.CurrentThread.ManagedThreadId);
awaitTestAsync();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i + "\n");
}
Console.Read();
}
private static async void awaitTestAsync()
{
Console.WriteLine("AwaitTestAsync方法的线程ID是:" + Thread.CurrentThread.ManagedThreadId);
var doSomethong = await Test();
Console.WriteLine("AwaitTestAsync方法的Await方法之后的线程ID是:" + Thread.CurrentThread.ManagedThreadId);
}
static async Task<int> Test()
{
Console.WriteLine("Test方法的线程ID是:" + Thread.CurrentThread.ManagedThreadId);
await Task.Run(() =>
{
Console.WriteLine("Test.Run方法的线程ID是:" + Thread.CurrentThread.ManagedThreadId);
for (int i = 5; i < 10; i++)
{
Console.WriteLine(i);
}
});
Console.WriteLine("Test方法的Await之后的线程ID是:" + Thread.CurrentThread.ManagedThreadId);
return 5;
}
}
}
WinForm程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.AppendText("Main方法的线程ID是:" + Thread.CurrentThread.ManagedThreadId + "\n");
awaitTestAsync();
for (int i = 90; i < 95; i++)
{
textBox1.AppendText(i + "\n");
}
}
private async void awaitTestAsync()
{
textBox1.AppendText("AwaitTestAsync方法的线程ID是:" + Thread.CurrentThread.ManagedThreadId + "\n");
var doSomethong = await Test();
textBox1.AppendText("AwaitTestAsync方法的Await方法之后的线程ID是:" + Thread.CurrentThread.ManagedThreadId + "\n*****\n值是:" + doSomethong);
}
private async Task<int> Test()
{
textBox1.AppendText("Test方法的线程ID是:" + Thread.CurrentThread.ManagedThreadId + "\n");
await Task.Run(() =>
{
int id = Thread.CurrentThread.ManagedThreadId;
this.Invoke(new EventHandler(delegate
{
textBox1.AppendText("Test.Run方法的线程ID是:" + id + "\n");
}));
for (int i = 95; i < 100; i++)
{
this.Invoke(new EventHandler(delegate
{
textBox1.AppendText(i.ToString() + "\n");
}));
}
});
int _id = Thread.CurrentThread.ManagedThreadId;
textBox1.AppendText("Test方法的Await之后的线程ID是:" + _id + "\n");
return 5;
}
}
}
相似的代码,但是结果却有很大的差异,有看出差异点嘛?
对于控制台应用程序来说,当await (Task<Void>/Task<Int>)前,线程是主线程,而await关键词