我正在使用可以有 n 个实例的后台 worker 。问题是 DoWork 方法(具有“发件人”参数,即 BackgroundWorker)调用产生回调的其他代码 - 因此我没有发件人。
如何确定当前代码运行的 BackgroundWorker?
例如:
private void SetupThread()
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(DoTheWork);
}
private void DoTheWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
// I know that sender here can be converted, but thats no good for me
MyClass.DoSomething(); // This will produce a callback(event) from MyClass
}
private void MethodCalledFromEventCallback()
{
// Here is where the actual work is being done. I need to determine which
// instance of the Backgroundworker is calling it so that i can use the
// UpdateProgress method
// I cannot do this :-( (BackgroundWorker)System.Threading.Thread.CurrentThread;
}
我可能只是忽略了一些东西(除非线程池是有序的 :-( )
我确信这可以通过 BackgroundWorker 轻松实现……有什么想法吗?
编辑
我的描述造成了一些困惑,这里有一些更多的事实:-) 1.) 我已经调用了 bw.RunWorkerAsync() 2.) 调用事件 MethodCalledFromEventCallback 的类不知道后台线程 3.) 我不能(由于设计要求)将 Backgroundworker 作为参数包含在内
谢谢:-)
最佳答案
据我所知,使用后台 worker 最好的方法可能是(假设你到目前为止提到的限制条件):
private void SetupThread()
{
BackgroundWorker bw = new BackgroundWorker();
// Assuming you need sender and e. If not, you can just send bw
bw.DoWork += new DoWorkEventHandler(DoTheWork);
}
private void DoTheWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
MyClass.Callback = () =>
{
((BackgroundWorker)bw).UpdateProgress(/*send your update here*/);
MethodCalledFromEventCallback();
};
MyClass.DoSomething(); // This will produce a callback(event) from MyClass
}
private void MethodCalledFromEventCallback()
{
// You've already sent an update by this point, so no background parameter required
}
关于c# - 如何从当前执行的方法中获取 BackgroundWorker 的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3232581/