开发者

C# BackgroundWorker looping back issues

private void btnTest_Click(object sender, RoutedEventArgs e)
{
    try
    {
        worker.DoWork += delegate(object s, DoWorkEventArgs args)
        {
            if (flag == false)
  开发者_StackOverflow          {
                setBtnText(btTest, "ReTest"); 
                flag = true;
            }
            else
            {
                setBtnText(btTest, "Test");
                flag = false;
            }
        };

        worker.RunWorkerAsync();
    }
    catch (Exception ex)
    {
        ErrorLogger(ex, "");
    }
}  

Ok, This is quite frustrating. Maybe I'm just having a brain fart. Basically I'm making a single button do 1/2 actions depending on how the flag is set. When I click btTest the first time, it works correctly and sets the button text to Retest. Now if I click it again, it sets it to Test, but then loops back to the beginning and sets it back to ReTest. I don't understand why it's looping back. It should either do if or else. Not if (click 1), then else to if (click 2), repeat on new click. It should (in my mind), do if (click 1), else (click 2), repeat on new click. Please help me understand this. Maybe it's how DoWork does things, I don't know. Thanks!


Essentially each time you click your button, you're adding another delegate to the worker with the same code. When you call RunWorkerAsync() it will execute the first delegate, and you will get your "Test" result, it will then execute the second delegate (same code) and set it back to "ReTest".

You can prove this to yourself by clicking it 3 times, you should see "Test" -> "ReTest" -> "Test".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜