从我的理解主要事情之一async
和await
要做的就是让代码易于读写-但使用它们等于产卵后台线程来执行持续时间长的逻辑?
我正在尝试最基本的例子.我在内联添加了一些评论.你能为我澄清一下吗?
// I don't understand why this method must be marked as `async`.
private async void button1_Click(object sender, EventArgs e)
{
Task<int> access = DoSomethingAsync();
// task independent stuff here
// this line is reached after the 5 seconds sleep from
// DoSomethingAsync() method. Shouldn't it be reached immediately?
int a = 1;
// from my understanding the waiting should be done here.
int x = await access;
}
async Task<int> DoSomethingAsync()
{
// is …
Run Code Online (Sandbox Code Playgroud) 有没有像这样编写方法的场景:
public async Task<SomeResult> DoSomethingAsync()
{
// Some synchronous code might or might not be here... //
return await DoAnotherThingAsync();
}
Run Code Online (Sandbox Code Playgroud)
而不是这个:
public Task<SomeResult> DoSomethingAsync()
{
// Some synchronous code might or might not be here... //
return DoAnotherThingAsync();
}
Run Code Online (Sandbox Code Playgroud)
会有意义吗?
为什么return await
在可以直接Task<T>
从内部DoAnotherThingAsync()
调用返回时使用构造?
我return await
在很多地方看到代码,我想我应该错过一些东西.但据我了解,在这种情况下不使用async/await关键字并直接返回Task将在功能上等效.为什么要增加附加await
层的额外开销?
使用"Async"后缀方法名称的约定是什么?
"Async"后缀是否应仅附加到使用async
修饰符声明的方法?
public async Task<bool> ConnectAsync()
Run Code Online (Sandbox Code Playgroud)
或者该方法刚刚返回Task<T>
还是足够Task
?
public Task<bool> ConnectAsync()
Run Code Online (Sandbox Code Playgroud) 在任务返回异步方法结束时,如果我调用另一个异步方法,我可以使用await
它或return
它的任务.每个的后果是什么?
Task FooAsync()
{
return BazAsync(); // Option A
}
async Task BarAsync()
{
await BazAsync(); // Option B
}
Run Code Online (Sandbox Code Playgroud) 我正在构建一个使用ADO.NET的.NET 4.0应用程序,所以我不能使用async/await.我不想要一个解决方案,但我想知道以下哪些实现最好,为什么.我的单元测试通过所有三个实现,但我想知道这三个之间的区别.
在我的第一个实现中,我将任务包装在另一个任务中.我认为搞两个任务对性能不利,但我不确定.
public virtual Task<IDataReader> ExecuteReaderAsync(IDbCommand dbCommand, CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
var sqlCommand = CheckIfSqlCommand(dbCommand);
PrepareExecuteReader(dbCommand);
return Task<IDataReader>
.Factory
.FromAsync(sqlCommand.BeginExecuteReader, sqlCommand.EndExecuteReader, null)
.Result;
}, cancellationToken);
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试将结果包装成一个TaskCompletionSource
所以我只有一个任务.
public virtual Task<IDataReader> ExecuteReaderAsync(IDbCommand dbCommand, CancellationToken cancellationToken)
{
var taskCompletionSource = new TaskCompletionSource<IDataReader>();
var sqlCommand = CheckIfSqlCommand(dbCommand);
PrepareExecuteReader(dbCommand);
var reader = Task<IDataReader>
.Factory
.FromAsync(sqlCommand.BeginExecuteReader, sqlCommand.EndExecuteReader, null)
.Result;
taskCompletionSource.SetResult(reader);
return taskCompletionSource.Task;
}
Run Code Online (Sandbox Code Playgroud)
我的最终解决方案是直接返回我创建的任务而不是包装它.
public virtual Task<IDataReader> ExecuteReaderAsync(IDbCommand dbCommand, CancellationToken cancellationToken)
{
var sqlCommand = CheckIfSqlCommand(dbCommand); …
Run Code Online (Sandbox Code Playgroud)