473,574 Members | 17,471 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Control.BeginIn voke

I have a question about BeginInvoke method found on the Control class.
To quote the docs:

"Executes the specified delegate asynchronously with the specified
arguments, on the thread that the control's underlying handle was
created on."

Which is fine, but I'm wondering how does this method get called
asynchronously if it's on the same thread we are working on? Surely it
blocks the thread until returned?

Jan 11 '06 #1
9 5650
John,

No, it doesn't. The documentation says that it invokes the method that
the control was created on, not the method that you were working on.

When you call Invoke, the method blocks until the call has been
completed on the UI thread. If you call BeginInvoke, the call is invoked
from the threadpool, and your code can continue asynchronously.

Note, you should not be calling Invoke/BeginInvoke if you are on the
main UI thread. Rather, you should just call the method you want to call.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"john doe" <sl********@gma il.com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
I have a question about BeginInvoke method found on the Control class.
To quote the docs:

"Executes the specified delegate asynchronously with the specified
arguments, on the thread that the control's underlying handle was
created on."

Which is fine, but I'm wondering how does this method get called
asynchronously if it's on the same thread we are working on? Surely it
blocks the thread until returned?

Jan 11 '06 #2
Nicholas Paldino [.NET/C# MVP] wrote:

<snip>
When you call Invoke, the method blocks until the call has been
completed on the UI thread. If you call BeginInvoke, the call is invoked
from the threadpool, and your code can continue asynchronously.


Do you mean that Control.BeginIn voke(delegate d) is effectively

SomeDelegate x = delegate { Control.Invoke( d); }
x.BeginInvoke() ;

?

(With *very* rough and ready syntax, of course.)

That seems a horrible way of working - doesn't it mean that with a
fairly busy UI you can easily run out of threadpool threads for tasks
which *wouldn't* block?

Jon

Jan 11 '06 #3
Jon,

No, it can't be what you described, because x.BeginInvoke is not
guaranteed to run on the UI thread. What Control.BeginIn voke is basically a
call to Control.Invoke on a ThreadPool thread. This is very different from
a call to BeginInvoke on the delegate.

And yes, with a fairly busy UI, you could run out of threadpool threads
(if you are updating it constantly from a worker thread with BeginInvoke),
but that's the case with anything that uses the threadpool. That's how the
threadpool is designed. If the task can not be completed on an available
thread, it queues it up, until a thread from the pool is available to
process it.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
Nicholas Paldino [.NET/C# MVP] wrote:

<snip>
When you call Invoke, the method blocks until the call has been
completed on the UI thread. If you call BeginInvoke, the call is invoked
from the threadpool, and your code can continue asynchronously.


Do you mean that Control.BeginIn voke(delegate d) is effectively

SomeDelegate x = delegate { Control.Invoke( d); }
x.BeginInvoke() ;

?

(With *very* rough and ready syntax, of course.)

That seems a horrible way of working - doesn't it mean that with a
fairly busy UI you can easily run out of threadpool threads for tasks
which *wouldn't* block?

Jon

Jan 11 '06 #4
Nicholas Paldino [.NET/C# MVP] wrote:
No, it can't be what you described, because x.BeginInvoke is not
guaranteed to run on the UI thread.
No, but it wouldn't need to be. Have another look at what I wrote -
it's d that needs to be executed on the UI thread. x is executed on the
thread pool thread (by calling x.BeginInvoke() and that in turn calls
Control.Invoke( d) (obviously using the appropriate control).
What Control.BeginIn voke is basically a call to Control.Invoke on a ThreadPool thread.
That's certainly what I was trying to get across :)
And yes, with a fairly busy UI, you could run out of threadpool threads
(if you are updating it constantly from a worker thread with BeginInvoke),
but that's the case with anything that uses the threadpool. That's how the
threadpool is designed. If the task can not be completed on an available
thread, it queues it up, until a thread from the pool is available to
process it.


It seems unnecessary to use the threadpool for this - it's unclear to
me why this can't just be put on the list of messages for the UI to
process. Ah well. Just another reason not to use the system
threadpool... I must update my threading pages to explain threadpool
deadlock at some stage (not that it's relevant here, I believe).

Jon

Jan 11 '06 #5
Actually, you are right, it does something like this (it creates its own
queue, not of threads, but of calls).

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
Nicholas Paldino [.NET/C# MVP] wrote:
No, it can't be what you described, because x.BeginInvoke is not
guaranteed to run on the UI thread.


No, but it wouldn't need to be. Have another look at what I wrote -
it's d that needs to be executed on the UI thread. x is executed on the
thread pool thread (by calling x.BeginInvoke() and that in turn calls
Control.Invoke( d) (obviously using the appropriate control).
What Control.BeginIn voke is basically a call to Control.Invoke on a
ThreadPool thread.


That's certainly what I was trying to get across :)
And yes, with a fairly busy UI, you could run out of threadpool
threads
(if you are updating it constantly from a worker thread with
BeginInvoke),
but that's the case with anything that uses the threadpool. That's how
the
threadpool is designed. If the task can not be completed on an available
thread, it queues it up, until a thread from the pool is available to
process it.


It seems unnecessary to use the threadpool for this - it's unclear to
me why this can't just be put on the list of messages for the UI to
process. Ah well. Just another reason not to use the system
threadpool... I must update my threading pages to explain threadpool
deadlock at some stage (not that it's relevant here, I believe).

Jon

Jan 11 '06 #6
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard .caspershouse.c om> wrote:
Actually, you are right, it does something like this (it creates its own
queue, not of threads, but of calls).


So it doesn't need the thread pool? Hmm... I can see I'm going to have
to investigate this :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 11 '06 #7
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.

Jan 12 '06 #8
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);
}
}

Jan 12 '06 #9

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
| Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard .caspershouse.c om> wrote:
| > Actually, you are right, it does something like this (it creates its
own
| > queue, not of threads, but of calls).
|
| So it doesn't need the thread pool? Hmm... I can see I'm going to have
| to investigate this :)
|
| --
| Jon Skeet - <sk***@pobox.co m>
| http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
| If replying to the group, please do not mail me too

None of the Invoke or BeginInvoke are actually using the ThreadPool. Both
directly call the method (and wait for return) when running on the UI
thread, else the delegate (and some more stuff like the execution context)
is queue'd in a private queue and a private user message is posted to the
windows queue. The window procedure responsible for handling the private
message picks up the item from the queue and executes the delegate target.
The difference between Invoke and BeginInvoke is that the first wait for the
message to be handled by the message handler, while the latter returns after
the message has been posted.
Willy.


Jan 12 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
6615
by: Grandma Wilkerson | last post by:
My question concerns the documentation for Control.BeginInvoke(). At one point is says: "Executes the specified delegate asynchronously with the specified arguments, on the thread that the control's underlying handle was created on." later in that same documentation page it says... "Note The BeginInvoke method calls the specified...
2
1578
by: Ingo Schasiepen | last post by:
Hi there, i'm evaluating if c# is suited to replace a script language. Most of the elements of this language can be replaced with a c#-library, but it also has some realtime-like elements. E.g., in this language, the following code is possible: { Int32 i=0; OnEvent ( ... ) {
9
7583
by: David Sworder | last post by:
Hi, I have a form that displays data (is that vague enough for you?). The data comes in on a thread-pool thread. Since the thread pool thread is not the same as the UI thread, the callback function of my form follows the standard design pattern: if(IsDisposed){ return; }
2
1354
by: VM | last post by:
How can I display the contents of a datatable in a windows datagrid while the table is being filled? Here's my summarized code: delegate void loadAuditFileToTableDelegate(); private void btn_run_Click(object sender, System.EventArgs e) { /* In Window form */ loadAuditFileToTableDelegate LoadAuditFileToTable = new...
6
15145
by: Valerie Hough | last post by:
I'm not entirely sure what the difference is between these two approaches. In order to avoid reentrant code, I was using Control.BeginInvoke in my UI to cause an asynchronous activity to be done on the UI's message loop. I began to get System.ExecutionEngineException errors so (on the theory of do something different if what you're doing...
5
2534
by: RWF | last post by:
I have a form, and from the form when a user clicks a button, it instantiates control that will be doing a lot of logic. I am trying to use System.Threading.ThreadPool.QueueUserWorkItem to spawn a background thread off the pool. I stepped through the logic, and everything seems to go through fine when the control is initialized, and my main...
2
4285
by: Jeroen | last post by:
We are experiencing a tuff-to-debug problem ever since we introduced a WebBrowser control into our failry large application. I'm not sure if the problem description below contains enough details, so if I need to elaborate on something please ask for it. We have a UserControl with a WebBrowser on it. This UserControl is instantiated a few...
7
5646
by: Ben Voigt [C++ MVP] | last post by:
As much as the CLR team assures us that it's ok to fire-and-forget Control.BeginInvoke, it seems it isn't. Maybe this is a bug. See for example: the comments in http://blogs.msdn.com/cbrumme/archive/2003/05/06/51385.aspx I was encountering a bug that disappeared when debugging. Not when a debugger is attached, mind you, but when I...
3
3858
by: Steve | last post by:
Hi All I am using VB.net 2008 and use timer controls within my applications Question Does the code in a Timer control.tick event run on a different thread to the main Application thread (UI Thread)? In some of the timers I update some UI controls e.g statusbar.labels and I
0
7817
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8081
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7833
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8119
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6482
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5635
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3771
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2254
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1359
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.