Reu*_*ass 14 c# task-parallel-library
如何引用我的代码在其中执行的任务?
ISomeInterface impl = new SomeImplementation();
Task.Factory.StartNew(() => impl.MethodFromSomeInterface(), new MyState());
...
void MethodFromSomeInterface()
{
Task currentTask = Task.GetCurrentTask(); // No such method?
MyState state = (MyState) currentTask.AsyncState();
}
Run Code Online (Sandbox Code Playgroud)
因为我正在调用一些接口方法,所以我不能只将新创建的任务作为附加参数传递.
由于您无法更改界面或实现,因此您必须自己完成,例如,使用ThreadStaticAttribute:
static class SomeInterfaceTask
{
[ThreadStatic]
static Task Current { get; set; }
}
...
ISomeInterface impl = new SomeImplementation();
Task task = null;
task = Task.Factory.StartNew(() =>
{
SomeInterfaceTask.Current = task;
impl.MethodFromSomeInterface();
}, new MyState());
...
void MethodFromSomeInterface()
{
Task currentTask = SomeInterfaceTask.Current;
MyState state = (MyState) currentTask.AsyncState();
}
Run Code Online (Sandbox Code Playgroud)