相关疑难解决方法(0)

为所有服务器端代码调用ConfigureAwait的最佳实践

当你有服务器端代码(即一些ApiController)并且你的函数是异步的 - 所以它们返回Task<SomeObject>- 你认为最好的做法是等待你调用的函数ConfigureAwait(false)吗?

我已经读过它更高效,因为它不必将线程上下文切换回原始线程上下文.但是,使用ASP.NET Web Api,如果您的请求是在一个线程上进行的,并且等待某些函数和调用ConfigureAwait(false),则可能会在返回ApiController函数的最终结果时将您置于不同的线程上.

我在下面输入了一个我正在谈论的例子:

public class CustomerController : ApiController
{
    public async Task<Customer> Get(int id)
    {
        // you are on a particular thread here
        var customer = await SomeAsyncFunctionThatGetsCustomer(id).ConfigureAwait(false);

        // now you are on a different thread!  will that cause problems?
        return customer;
    }
}
Run Code Online (Sandbox Code Playgroud)

c# task-parallel-library async-await asp.net-web-api

517
推荐指数
4
解决办法
18万
查看次数

同步调用异步方法

我有一个async方法:

public async Task<string> GenerateCodeAsync()
{
    string code = await GenerateCodeService.GenerateCodeAsync();
    return code;
}
Run Code Online (Sandbox Code Playgroud)

我需要从同步方法中调用此方法.

如何在不必复制GenerateCodeAsync方法的情况下执行此操作以使其同步工作?

更新

然而找不到合理的解决方案

但是,我看到HttpClient已经实现了这种模式

using (HttpClient client = new HttpClient())
{
    // async
    HttpResponseMessage responseAsync = await client.GetAsync(url);

    // sync
    HttpResponseMessage responseSync = client.GetAsync(url).Result;
}
Run Code Online (Sandbox Code Playgroud)

c# asp.net asynchronous task-parallel-library async-await

216
推荐指数
7
解决办法
21万
查看次数