Search code examples
c#.netbackgroundworkerinvoke

Method.Invoke() behaving strangely C# .NET BackgroundWorker


I have the following code with some detail taken out:

private void bkgdProcessData_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    bkgdProcessData.ReportProgress(0);

    bool rdPickChecked = false;
    bool rdAutoChecked = true;
    int lbLengthsSelectedIndex = 0;
    string lbLengthsText = "";

    BeginInvoke(new MethodInvoker(() => {
        rdPickChecked = rdPick.Checked;
        rdAutoChecked = rdAuto.Checked;
        lbLengthsSelectedIndex = lbLengths.SelectedIndex;
        lbLengthsText = lbLengths.SelectedItem.ToString();
    }));

    if (rdPickChecked == true && e.Cancel == false)
    {
        if (lbLengthsSelectedIndex < 0)
        {
            ...
        }
        else if (SortedOrderedPieces[0].PieceLength > double.Parse(lbLengthsText))
        {
            ...
        }
        else
            ...
    }
    else if (rdAutoChecked == true && e.Cancel == false)
    {
        ...
    }
}

As you can see, this whole procedure is the BackgroundWorker. I am using MethodInvoke() to access UI elements and write them to variables in this procedure.

My problem is, when I put a breakpoint at the beginning of this procedure and step through it, it sets the variables correctly and the program works fine, but if I remove the breakpoint and just run it, the variables don't set and my program doesn't work. Am I going about this in the wrong way?


Solution

  • You're calling BeginInvoke, which is asynchronous - it will execute the given delegate in the UI thread, but not block the currently executing thread... which means it's highly likely that you'll end up using the variables in the rest of your method before the delegate has executed.

    One solution is just to use Invoke instead of BeginInvoke.

    Another option is to pick up the values from the UI before starting the BackgroundWorker, so that you don't need to go back to the UI thread. Exactly how you'd do that will depend on how and where you're launching the background worker.