john said:
I've just read this article:
http://www.codeproject.com/csharp/begininvoke.asp which at the bottom
says
"Control.BeginInvoke does not use a threadpool thread, it does a
PostMessage to the target window handle and returns."
Who is right? Personally I know who I trust more, but I'd like to know
how the information both you and the author of the article above have
go this extra information from.
There's a fairly easy way to find out, fortunately. Here's some code
which does the following:
1) Makes sure that the ThreadPool has created all the threads it can
use
2) Jams up the ThreadPool with jobs which just sleep and indicate when
they're done
3) Checks there are no available threads
4) Creates a form
5) Starts a new background task (see 7)
6) Runs the form
7) After sleeping, the background task calls BeginInvoke on the form
with a delegate
8) The delegate indicates when it's done
Running it, the delegate used as an argument to BeginInvoke gets called
even though the ThreadPool has no available threads. This suggests that
the ThreadPool isn't involved.
Of course, I'm happy to be told why my test is broken
Jon
using System;
using System.Windows.Forms;
using System.Threading;
class Test
{
static Form f;
static void Main()
{
// Crank the thread-pool up to have all its threads running
int threads, ioc, ignored;
ThreadPool.GetMinThreads(out ignored, out ioc);
ThreadPool.GetMaxThreads(out threads, out ignored);
ThreadPool.SetMinThreads(threads, ioc);
// Jam up the threadpool
for (int i=0; i < 100; i++)
{
ThreadPool.QueueUserWorkItem(new
WaitCallback(SleepWorkItem), i);
}
// Let them all get scheduled
Thread.Sleep(500);
ThreadPool.GetAvailableThreads(out threads, out ignored);
Console.WriteLine ("Number of available ThreadPool threads:
{0}", threads);
f = new Form();
new Thread (new ThreadStart(BackgroundThread)).Start();
Application.Run(f);
}
static void BackgroundThread()
{
// Wait for the form to be shown
Thread.Sleep (1000);
f.BeginInvoke (new EventHandler(RunInUIThread));
Console.WriteLine ("BackgroundThread finishing");
}
static void RunInUIThread(object sender, EventArgs e)
{
Console.WriteLine ("RunInUIThread executing");
}
static void SleepWorkItem(object state)
{
// Wait a long time
Thread.Sleep(5000);
Console.WriteLine ("Sleep item {0} finishing", state);
}
}