简体   繁体   中英

C# event firing null from backgroundWorker

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);
    }

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);

the OnStatusChange in the RaiseEvent is always null and therefore never gets fired. The BwExecute_DoWork is:

 private void BwExecute_DoWork(object sender, DoWorkEventArgs e)
    {
        object[] parameters = e.Argument as object[];
        String currentFunc = parameters[0].ToString();
        String partProgramFilename = parameters[1].ToString();
        List<String> varsValueList = (List<String>)parameters[2];

        ExecuteJob(currentFunc,partProgramFilename, varsValueList);
    }

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

** ADD ** I noticed that 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM