jeudi 8 novembre 2018

Background Worker won't receive CancellationPending in c# WinForm application

I have a problem with backgroundworkers in my WinForm application. Here is my scenario: I have a background workers that starts in OnLoad form event. Then I have a checkbox on the form to stop/start the workers. When I uncheck the box the event call the cancelAsync() method, but the worker don't receive CancellationPending. To debug this problem I have tried to add a Button on the form that perform the same as the CheckedChanged event, in this case it works???!!!

This is a snippet of my code:

The workers ...

private void BwMB_DoWork(object sender, DoWorkEventArgs e)
{
    bwMBExitEvent.Reset();

    bool loop = true;
    while (loop)
    {
        if (bwMB.CancellationPending)
        {
            loop = false;
        }

        ... other code ...
    }

    e.Cancel = true;
    bwMBExitEvent.Set();
}

The CheckedChanged event ...

private void checkBoxModBus_CheckedChanged(object sender, EventArgs e)
{
    try
    {   
        if (checkBoxModBus.Checked)
        {
            if (!bwMB.IsBusy)
                bwMB.RunWorkerAsync();
        }
        else
        {
            if (bwMB.IsBusy)
            {
                bwMB.CancelAsync();
                bwMBExitEvent.WaitOne();
            }
        }
     }
     catch(Exception ex)
     {
        Console.WriteLine(ex.Message);
     }
}

And the button click event for debug ...

private void button2_Click(object sender, EventArgs e)
{
    bwMB.CancelAsync();
    bwMBExitEvent.WaitOne();
}

When I click on the button the worker receives the cancellation signals and exit loop setting the bwMBExitEvent (ManualResetEvent). In this way the click event WaitOne end waiting. When I uncheck the box the worker, stop running, but don't receive the signal, so don't ends the loop and the event is not set. The CheckedChanged's WaitOne never ends.

I hope I habe been clear. Sorry for my bad english, and thanks for tour help. Leonardo.




Aucun commentaire:

Enregistrer un commentaire