How can we create a callcontext for async .net methods?

久未见 提交于 2019-12-13 18:33:55

问题


In a synchronous environment, it is easy to create a scoped context which allows you to attach out-of-band context to your current thread. Examples of this are the current TransactionScope or thread-static logging context.

using (new MyContext(5))
    Assert.Equal(5, MyContext.Current);

Assert.Equal(null, MyContext.Current);

It is easy to implement the context using a combination of IDisposable and a thread-static field.

Obviously, this falls apart when using async methods, because the context is based on a thread-static field. So, this fails:

using (new MyContext(5))
{
    Assert.Equal(5, MyContext.Current);

    await DoSomethingAsync();

    Assert.Equal(5, MyContext.Current);
}

And of course we would also want that the context is passed to the async methods in the call chain, so this should work as well:

using (new MyContext(5))
{
    Assert.Equal(5, MyContext.Current);

    await AssertContextIs(5);
}

Does anyone have an idea how this could be implemented? Losing out-of-band context when using the async/await pattern makes some pieces of the code really ugly.

Think of async WebAPI calls where you would like to use request-based context for logging purposes. You want your logger deep in the call stack to be aware of the request ID without having the need to pass that request ID all the way through the call stack using parameters.

Thanks for any help!


回答1:


The best solution is to use HttpContext.Current.Items in ASP.NET, or IOwinRequest.[Get|Set] in OWIN. Yes, this does mean passing the request object everywhere, which makes sense if you think of your "context value" as belonging to that request. If you're uncomfortable with a "library" method knowing about OWIN, then it's easy to write a "context wrapper" object and pass that around instead.

However, if you are sure you don't want to pass anything around, then you can use LogicalCallContext with immutable data as I describe on my blog. If you're just concerned about logging, then you may find my AsyncDiagnostics library useful - it uses PostSharp to inject method names, and you can add your own info into the "async stack" as well.




回答2:


If you are in an hosted environment (you are talking about WebAPI) you should use the Request context (HttpContext.Current), not the thread as you don't manage threads and don't know when/if the original thread will be available neither how to get back on it.

The request context is properly handled using the await keyword.



来源:https://stackoverflow.com/questions/26013358/how-can-we-create-a-callcontext-for-async-net-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!