Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a library which fires events through this code:

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


and

C#
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

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



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
Posted
Updated 9-Nov-15 22:42pm
v2

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

instead?
 
Share this answer
 
Comments
Patrick70__ 10-Nov-15 5:21am    
But in the backgroundWorker OnstatusChange is null so invoke or not the method is not called.
phil.o 10-Nov-15 5:28am    
Can you please show the content of the BwExecute_DoWork method?
(NOT IN COMMENT, please press the 'Improve' button under your question :) )
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900