0

Possible Duplicate:
How to stop BackgroundWorker on Form's Closing event?

I have some code in a Windows Form a bit like this:

button1_Click(object sender, EventArgs e)
{
  Widget myWidget = new Widget(...bunch of constructor parameters...);
  myWidget.Property1 = "blah"; // other properties get set here too...
  myWidget.InterestingThingHappened += InterestingThingHappened;

  Parallel.Invoke(myWidget.RunInterestingLongRunningProcess());
}

private void InterestingThingHappened(object sender, EventArgs e)
{
  myLabel.Invoke(new Action(() => myLabel.Text = "An interesting thing happened!"))
}

When I run it, the application just freezes until I kill it in Task Manager. Then I see an Exception saying 'Invoke or BeginInvoke cannot be called on a control until the window handle has been created.' button1_Click is clearly a control event handler, so the form is fully created before this code runs. I have absolutely no idea what this means. Can anyone help?

Community
  • 1
  • 1
David
  • 15,750
  • 22
  • 90
  • 150
  • While Googling this problem, I would never have recognised the question you posted as being the same as mine. It still don't see that it is... – David Sep 24 '12 at 22:23
  • This is in no sense a duplicate of the linked question. My code doesn't use BackgroundWorker. I'm not trying to close a form. I wonder if there's a way to appeal this? – David Oct 01 '12 at 16:20

1 Answers1

0

Using BeginInvoke() rather than Invoke() fixed the problem completely. The UI updated in real time. Why? Who knows?

David
  • 15,750
  • 22
  • 90
  • 150
  • I've no clue why your app didn't work and wouldn't dare post an answer but, as a general rule, always use asynchronous inter-thread comms if at all possible. The deadlock-potential of synchronous comms is just too high. – Martin James Sep 25 '12 at 00:08
  • Thanks for your comment, but I'm afraid I don't know what asynchronous or synchronous inter-thread comms are. Can you be more specific? – David Sep 25 '12 at 10:25