0

I am running the following code when i click on a button:

                foreach (string item in urlQueue)
                {

                    log("creating job " + iia.ToString());
                    _smartThreadPool.QueueWorkItem(
                        new Amib.Threading.Func<string, int, int, string, int>(checkURLSmart),
                        item, iia, 5000, kryptonTextBox1.Text);

                    iia++;
                }

                Application.DoEvents();

                _smartThreadPool.Start();

                _smartThreadPool.WaitForIdle();
                _smartThreadPool.Shutdown();

For some reason this is blocking the UI thread, any ideas how to fix this? I want the UI to be responsive while the queue is working

Elvin
  • 367
  • 3
  • 5
  • 16
  • 'ThreadPool.WaitForIdle()' - don't wait in GUI event handlers. – Martin James Oct 09 '12 at 08:16
  • Not in a GUI event handler. One way would be to queue a work item that uses the WaitAll() method to wait for all the other WorkItems issued in the loop and signal completion to the GUI thread, (PostMessage(), BeginInvoke(), whatever), in the PostExecute callback of the 'WaitAll'workItem. – Martin James Oct 09 '12 at 08:45
  • Not sure i understand :/ Could you write a small example? – Elvin Oct 09 '12 at 08:57

1 Answers1

0

You shouldn't call WaitForIdle() in GUI thread. Use http://msdn.microsoft.com/en-us/library/a06c0dc2.aspx in .NET or http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html invokeLater() in Java instead.

This mechanism put your code in queue for execution in GUI thread. So you are able to update GUI view with processed data in callback parameters.

Also see explanation about differences between Invoke & BeginInvoke: What's the difference between Invoke() and BeginInvoke()

Community
  • 1
  • 1
Taky
  • 5,284
  • 1
  • 20
  • 29
  • How would i use that for WaitForIdle? Isent that only for controls? – Elvin Oct 09 '12 at 11:04
  • Why do you need call WaitForIdle? I suppose you perform some updating logic after. So better is to update UI from backgrounds threads using appropriate framework mechanism. – Taky Oct 11 '12 at 10:35