john doe wrote:
I've just read this article:
http://www.codeproject.com/csharp/begininvoke.asp which at the bottom
says
"Control.BeginI nvoke 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.Threadin g;
class Test
{
static Form f;
static void Main()
{
// Crank the thread-pool up to have all its threads running
int threads, ioc, ignored;
ThreadPool.GetM inThreads(out ignored, out ioc);
ThreadPool.GetM axThreads(out threads, out ignored);
ThreadPool.SetM inThreads(threa ds, ioc);
// Jam up the threadpool
for (int i=0; i < 100; i++)
{
ThreadPool.Queu eUserWorkItem(n ew
WaitCallback(Sl eepWorkItem), i);
}
// Let them all get scheduled
Thread.Sleep(50 0);
ThreadPool.GetA vailableThreads (out threads, out ignored);
Console.WriteLi ne ("Number of available ThreadPool threads:
{0}", threads);
f = new Form();
new Thread (new ThreadStart(Bac kgroundThread)) .Start();
Application.Run (f);
}
static void BackgroundThrea d()
{
// Wait for the form to be shown
Thread.Sleep (1000);
f.BeginInvoke (new EventHandler(Ru nInUIThread));
Console.WriteLi ne ("BackgroundThr ead finishing");
}
static void RunInUIThread(o bject sender, EventArgs e)
{
Console.WriteLi ne ("RunInUIThr ead executing");
}
static void SleepWorkItem(o bject state)
{
// Wait a long time
Thread.Sleep(50 00);
Console.WriteLi ne ("Sleep item {0} finishing", state);
}
}