111,105
社区成员




// TASK EXAMPLE
async Task Task_MethodAsync()
{
// The body of an async method is expected to contain an awaited
// asynchronous call.
// Task.Delay is a placeholder for actual work.
await Task.Delay(2000);
// Task.Delay delays the following line by two seconds.
textBox1.Text += String.Format("\r\nSorry for the delay. . . .\r\n");
// This method has no return statement, so its return type is Task.
}
async Task abc()
就相当于void abc(Action callback)
而async Task<int> abc
就相当于void abc(Action<int> callback)
,async/await 语法是让你把异步回调代码用顺序代码的风格来写,但是它也制造了麻烦,使得不求甚解的人会越来越糊涂。
static void Main(string[] args)
{
Task<bool> task = Task.Factory.StartNew(new Func<bool>(() =>
{
return true;
}));
bool result = task.Result;
Task task2 = Task_MethodAsync();
task2.Start();
// 无 result
Task<string> task3 = Task_MethodAsync2();
task3.Start();
string result3 = task3.Result;
}
static async Task Task_MethodAsync()
{
// The body of an async method is expected to contain an awaited
// asynchronous call.
// Task.Delay is a placeholder for actual work.
await Task.Delay(2000);
// Task.Delay delays the following line by two seconds.
//textBox1.Text += String.Format("\r\nSorry for the delay. . . .\r\n");
// This method has no return statement, so its return type is Task.
}
static async Task<string> Task_MethodAsync2()
{
await Task.Delay(2000);
return "123";
}