如何获得当前任务参考? [英] How to get the current task reference?
本文介绍了如何获得当前任务参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何引用执行代码的任务?
How can I get reference to the task my code is executed within?
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();
}
由于我在调用某种接口方法,所以我不能仅仅通过新创建的任务作为附加参数。
Since I'm calling some interface method, I can't just pass the newly created task as an additional parameter.
推荐答案
由于您无法更改接口或实现,因此必须自己完成操作,例如使用 ThreadStaticAttribute
:
Since you can't change the interface nor the implementation, you'll have to do it yourself, e.g., using 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();
}
这篇关于如何获得当前任务参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文