当你有服务器端代码(即一些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) 从主AppDomain,我试图调用以不同AppDomain中实例化的类型定义的异步方法。
例如,以下类型MyClass继承MarshalByRefObject自新AppDomain并在其中实例化:
public class MyClass : MarshalByRefObject
{
public async Task<string> FooAsync()
{
await Task.Delay(1000);
return "Foo";
}
}
Run Code Online (Sandbox Code Playgroud)
在主AppDomain中,我创建一个新的AppDomain并在此AppDomain中创建MyClass的实例,然后调用异步方法。
var appDomain = AppDomain.CreateDomain("MyDomain");
var myClass = (MyClass)appDomain.CreateInstanceAndUnwrap(typeof(MyClass).Assembly.FullName, typeof(MyClass).FullName);
await myClass.FooAsync(); // BAM !
Run Code Online (Sandbox Code Playgroud)
当然,SerializationException当我尝试进行调用时会收到一个,因为该Task类型不继承自MarshalByRefObject,也不可序列化。
我怎样才能解决这个问题?我真的很希望能够从另一个AppDomain中实例化的类型上调用/等待异步方法...有没有办法?
谢谢 !