C#事件从backgroundWorker触发null [英] C# event firing null from backgroundWorker

查看:100
本文介绍了C#事件从backgroundWorker触发null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过此代码触发事件的库:



I have a library which fires events through this code:

public delegate void ChangedEventHandler(String currentFunction, String PCDMessage, ePcdEventType pcdEventType, ePcdEvent pcdEvent);
  public event ChangedEventHandler OnStatusChange;











and

protected virtual void RaiseEvent(String strCurrentFunction, String strMessage, ePcdEventType pcdEventType, ePcdEvent pcdEvent)
    {
        if (OnStatusChange != null)
            OnStatusChange(strCurrentFunction, strMessage, pcdEventType, pcdEvent);
    }





一切正常,但当我从以下backgroundWorker中解雇活动时





everything works fine but when I fire the event from the following backgroundWorker

bwExecute = new BackgroundWorker();
bwExecute.DoWork += BwExecute_DoWork;
bwExecute.RunWorkerCompleted += Bg_RunWorkerCompleted;
object[] parameters = new object[] { currentFunc, partProgramFilename, varsValuesList};
bwExecute.RunWorkerAsync(parameters);







和RaiseEvent在ExecuteJob中被触发例程就像它们在代码的其他部分被触发一样。



所以简而言之,只有在backgroundWorker内部调用时,在RaiseEvent中调用OnStatusChange总是为空并且所以事件没有被解雇。我总是以同样的方式在后台工作者的外部和内部调用RaiseEvent(...)。现在明白了问题,解决方案是什么?



**编辑**我正在使用C#WPF,但我认为这没有任何区别。 />


感谢任何帮助Patrick




and the RaiseEvent are fired in the ExecuteJob routine just as they are fired in the other part of the code.

So in short ONLY when called inside the backgroundWorker the OnStatusChange when called inside the RaiseEvent is ALWAYS NULL and so the event is not fired. I always call the RaiseEvent(...) in the same way both outside and inside the background worker. Now understood the problem, what is the solution?

**EDIT** I'm using C# WPF but I don't think this makes any difference.

Thank for any help Patrick

推荐答案

你可以试试:

Can you try:
if (OnStatusChange != null) {
   OnStatusChange.Invoke(strCurrentFunction, strMessage, pcdEventType, pcdEvent);
}



代替?


instead?


我找到了解决方案,这是显而易见的。现在很明显了。

在主窗口中我调用了库函数,只有在我从类的实例中分离事件之后才会这样。

因此,如果没有后台启动,则执行是串行的首先它执行代码然后它分离事件。

但是当启动backgroundWorker时,执行是并行的,因此在执行代码时,它会在上述代码终止之前分离。从这个错误。请大家帮忙。
I found the solution and that is so obvious. Now it's obvious.
From the main window I called the library functions and only after those I detach the event from the instance of the class.
So if launched without backgroundWorked the execution is serial so first it execute the code and then it detaches the event.
But when launching the backgroundWorker the execution is parallel so while executing the code it detaches the even before that the aforementioned code is terminated. From this the error. Thanx everyone for helping.


这篇关于C#事件从backgroundWorker触发null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆