我是使用async和await的新手。我创建了一个N层控制台应用程序,它有一个业务逻辑层和一个存储库层。在将数据返回给用户之前,用户调用的一些操作会调用业务,然后调用存储库需要几分钟才能执行。我对使用异步任务和等待标记的方法感到困惑。在应用程序等待几分钟后返回数据时,我是否应该在Console应用程序中创建调用Business层异步的方法?或者业务层或存储库中的方法是否应标记为异步?或者说所有图层中的所有方法都标记为异步?
我基本上希望应用程序以下列方式工作:
1) Application starts
2) Business layer called to retrieve data, the
application code moves on to make the next call to business layer, and
then the next business layer while allowing the other faster running
operations to return their data/text in the meantime, while the longer
running operations are still running.
3) the longer running
applications complete at any point during the execution and output to
the console when they have completed eg not in any necessary order due
to the fact the methods are asynchronous.
我该如何实现?我知道这是可能的,但我不知道将异步和等待的方法放在哪里。
答案 0 :(得分:3)
创建一个MainAsync
方法,并在正常的Main
方法中等待它:
public static void Main()
{
MainAsync().ConfigureAwait(false).GetAwaiter().GetResult();
}
public static async Task MainAsync()
{
var service = new ServiceA();
var result = await service.GetValue().ConfigureAwait(false);
Console.WriteLine("Result: {0}", result);
}
public class ServiceA
{
private Repository _repository;
public ServiceA()
{
_repository = new Repository();
}
public async Task<int> GetValue()
{
var v = await _repository.Get().ConfigureAwait(false);
// business logic...
return v * 3;
}
}
public class Repository
{
public Task<int> Get()
{
return Task.FromResult(10);
}
}
然后异步/等待所有事情!