c# – 如何从当前执行的方法中获取BackgroundWorker的实例?
发布时间:2020-12-16 01:37:00 所属栏目:百科 来源:网络整理
导读:我正在使用可以有n个实例的后台工作程序.问题是DoWork方法(具有’sender’参数,即BackgroundWorker)调用产生回调的其他代码 – 因此我没有发件人. 如何确定当前代码运行的BackgroundWorker? 例如: private void SetupThread(){BackgroundWorker bw = new B
我正在使用可以有n个实例的后台工作程序.问题是DoWork方法(具有’sender’参数,即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很容易实现……任何想法? 编辑 我在我的描述中引起了一些困惑,这里有一些更多的事实:-) 谢谢 :-) 解决方法
据我所知,使用后台工作者可能最好的方法是(假设你到目前为止提到的约束):
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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |