开始编辑
要做到这一点,“正确”的方法(pre4.5)是使用SynchronizationContext,如下所示:http://msdn.microsoft.com/en-us/magazine/gg598924.aspx
我相信在4.5中,SynchronizationContext会自动使用异步/等待关键字来处理,但是还没有完成足够的工作来确认。
在4.0中,您可能希望利用"TaskScheduler.FromCurrentSynchronizationContext“来捕获当前线程的上下文(在我的示例中,这将包括HttpContext,但BCL的各个部分提供类似的构造)。
端编辑
主要问题是:
是以下与任务共享“上下文”的“安全”机制?
在我的用例中,如果没有过多的细节,就不可能将上下文直接推入操作中。
public static class ContextCaller{
[ThreadStatic]
public static object SharedState;
public static Task InvokeWithContext(this Action theAction){
//We're still running in the "outer" context,
//so we can collect a variable and store it in the thread-static
//field by closing it into the task.
var context = new object();
var t = new Task(()=>{
try{
//close in the context
SharedState = context;
theAction();
}
finally{
//teardown the shared state.
SharedState = null;
}
});
t.Start();
return t;
}
}现在是客户端代码:
//client code:
Action doWork = ()=>{
var state = ContextCaller.SharedState;
//do work on state, potentially throwing an exception in the process.
};
//cause the task to be invoked with some data available only on this thread.
doWork.InvokeWithContext();根据我对任务与线程之间的关系的理解,上面的内容应该是安全的,因为:
除了在参数中显式关闭"theAction“之外,还有其他更好的模式来定义任务的上下文吗?
发布于 2012-12-14 22:59:04
我不认为有任何技术原因可以解释为什么您的代码不能正常工作。
但我也认为这样做是一种糟糕的做法,只有在没有其他方法的情况下,我才会使用这样的方法。我认为,添加另一个使用Action<object> (甚至更好的是使用强类型参数)的方法重载并不是一个重大的改变。
https://stackoverflow.com/questions/13883769
复制相似问题