Use BackgroundWorker with any class

BackgroundWorker works only with the classes that implements interface ISynchronizeInvoke – in order to use BackgroundWorker with any class necessary to make the following changes in the code.

The code after the changes ( BackgroundWorker.cs ):

private void InvokeDelegate(Delegate del, params object[] args)
{
    ISynchronizeInvoke synchronizer = del.Target as ISynchronizeInvoke;
    try
    {
        if(synchronizer != null) //A Windows Forms object
        {
            if (synchronizer.InvokeRequired == false)
            {
                del.DynamicInvoke(args);
                return;
            }
            synchronizer.Invoke(del, args);
        }
        else //Not a Windows Forms object
        {
            del.DynamicInvoke(args);
        }
    }
    catch (Exception e)
    {
        Trace.WriteLine(e.Message);
    }
}

 

 

Thanks to Roy Osherove for help in the solution of this problem


 
 
 

Leave a Reply