3 回答
TA贡献1805条经验 获得超10个赞
async
/await
static async Task TestAsync(){ await Task.Delay(1000);}void Form_Load(object sender, EventArgs e){ TestAsync().Wait(); // dead-lock here}
Task TestAsync() { return Task.Delay(1000);}
async Task
Task
await task
, task.Wait()
, task.Result
task.GetAwaiter().GetResult()
async
OneTestAsync
AnotherTestAsync
static async Task OneTestAsync(int n){ await Task.Delay(n);}static Task AnotherTestAsync(int n){ return Task.Delay(n);} // call DoTestAsync with either OneTestAsync or AnotherTestAsync as whatTeststatic void DoTestAsync(Func<int, Task> whatTest, int n){ Task task = null; try { // start the task task = whatTest(n); // do some other stuff, // while the task is pending Console.Write("Press enter to continue"); Console.ReadLine(); task.Wait(); } catch (Exception ex) { Console.Write("Error: " + ex.Message); }}
DoTestAsync(OneTestAsync, -2)
Press enter to continue Error: One or more errors occurred.await Task.Delay Error: 2nd
DoTestAsync(AnotherTestAsync, -2)
DoTestAsync
Error: The value needs to be either -1 (signifying an infinite timeout), 0 or a positive integer. Parameter name: millisecondsDelayError: 1st
Task.Delay(-2)
Task.Delay(1000)
async void
async Task
async void
SynchronizationContext.Post
SynchronizationContext.Current != null)
ThreadPool.QueueUserWorkItem
Qasync
Task
A
// asyncasync Task<int> MethodAsync(int arg){ if (arg < 0) throw new ArgumentException("arg"); // ... return 42 + arg;}// non-asyncTask<int> MethodAsync(int arg){ var task = new Task<int>(() => { if (arg < 0) throw new ArgumentException("arg"); // ... return 42 + arg; }); task.RunSynchronously(TaskScheduler.Default); return task;}
RunSynchronously
TA贡献1826条经验 获得超6个赞
.之间的区别是什么? async Task TestAsync() { await Task.Delay(1000);}
和 Task TestAsync() { return Task.Delay(1000);}?
Func<int> MakeFunction(){ Func<int> f = ()=>1; return ()=>f();}
Func<int> MakeFunction(){ return ()=>1;}
?
- 3 回答
- 0 关注
- 3800 浏览
添加回答
举报