473,696 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Advanced Windows Form message priority / threading.

Hello again,
I've already placed a few posts on this topic.
This time i've a simple application that exhibits my problem,
I've placed sample solution 8k on my website should anyone be interested in
having a look. http://briankeating.net/transfer/test.zip

To recap the problem I expected (and found).
I've a main GUI thead (main form), this GUI thread has an UpdateTextBox
function that appends a string in a textbox and It also has a button that
stops my worker thread(s) form calling Invoke on main thead.

private void UpdateTextBox(s tring strText)
{
System.Diagnost ics.Debug.Asser t(InvokeRequire d != true, "Invoke was
required", "calling begin invoke not on
the gui thread");
richTextBox1.Fo cus();
richTextBox1.Ap pendText(strTex t);
}

When my form loads I start two worker threads and these threads just loop
around and call Invoke on my main Form with a string to display.

private void ThreadEntryPoin t()
{
while (!bStop)
{
string str = "Thread Id: " + GetHashCode() + ",\t" + nCount.ToString () + "
This is a passing string\r\n";

Invoke(new UpdateTextboxDe legate(UpdateTe xtBox), new object[] {str});
Interlocked.Inc rement(ref nCount);
//Thread.Sleep(10 00); //slow sending
Thread.Sleep(10 ); //fast sending
} //end while

MessageBox.Show (Thread.Current Thread.ToString () + " thread closing");
}

Now if my worker threads are slow sending i.e. I call Thread.Sleep(10 00);
i.e. wait a seond between each invoke call on the gui thread, then I have no
problem I can click my button and the event handler is called

private void button1_Click(o bject sender, System.EventArg s e)
{
bStop = true;
}

However if my two threads are sending fast (only waiting 10 miliseconds)
then my GUI thread is so busy processing these update events that if i click
the stop button nothing happens.

.... Hope that kinda clears things up about a GUI thread becoming unresponsive.

So what are my options?
I'm thinking that Inovke is basically like SendMessage so maybe somehow i
can replace the windows message loop to do the following, (basically
prioritised message queue)
loop
peek all windows messages and process them, (get/dispatch)
then peek for one of my Inoke calls (get/dispatch)
endloop

Now people that have helped me already may be asking what has as this to do
with windows running in different threads, well the reason I want to do this
is, say for example i have 2 windows in my application, one window is busy
receiving messages from a worker thread (so this is gonna become
unresponsive), i wouldn't like all other windows to become unresponsive too),
switching between windows will require my busy thread to handle some window
messages (loose focus maybe etc) so a prioritised message queue will allow
this, hey maybe this is enough I'll keep at it and see what happens.

But I gues this post comes down to one question,
Is there anyway I can plug into a windows forms message queue and check for
pending invoke calls as described above?

Thanks for any help
Brian.

p.s.
This is only a sample test app, so it's not perfect for many a reason,
I realise the two worker threads calling Invoke is pretty much the same as
One worker thread calling invoke.
clicking close on the forms gets executed straight away for some reason
(maybe it's handled differently?)
Clicking close will throw an exception cause i havn't stopped the worker
thread(s) from sending.
Nov 16 '05 #1
3 7401
I've been thinking about this a little more,
an call to Control.Invoke is basically a function all onto my Form (control)
from the ThreadPool,

If i want my Invoke calls in my message queue I prob have to use events? or
maybe PInvoke on SendMessage etc?
Hopefully these will arrive on my message que and I can introduce a
prioritised system?

thanks
Brian

"Brian Keating EI9FXB" wrote:
Hello again,
I've already placed a few posts on this topic.
This time i've a simple application that exhibits my problem,
I've placed sample solution 8k on my website should anyone be interested in
having a look. http://briankeating.net/transfer/test.zip

To recap the problem I expected (and found).
I've a main GUI thead (main form), this GUI thread has an UpdateTextBox
function that appends a string in a textbox and It also has a button that
stops my worker thread(s) form calling Invoke on main thead.

private void UpdateTextBox(s tring strText)
{
System.Diagnost ics.Debug.Asser t(InvokeRequire d != true, "Invoke was
required", "calling begin invoke not on
the gui thread");
richTextBox1.Fo cus();
richTextBox1.Ap pendText(strTex t);
}

When my form loads I start two worker threads and these threads just loop
around and call Invoke on my main Form with a string to display.

private void ThreadEntryPoin t()
{
while (!bStop)
{
string str = "Thread Id: " + GetHashCode() + ",\t" + nCount.ToString () + "
This is a passing string\r\n";

Invoke(new UpdateTextboxDe legate(UpdateTe xtBox), new object[] {str});
Interlocked.Inc rement(ref nCount);
//Thread.Sleep(10 00); //slow sending
Thread.Sleep(10 ); //fast sending
} //end while

MessageBox.Show (Thread.Current Thread.ToString () + " thread closing");
}

Now if my worker threads are slow sending i.e. I call Thread.Sleep(10 00);
i.e. wait a seond between each invoke call on the gui thread, then I have no
problem I can click my button and the event handler is called

private void button1_Click(o bject sender, System.EventArg s e)
{
bStop = true;
}

However if my two threads are sending fast (only waiting 10 miliseconds)
then my GUI thread is so busy processing these update events that if i click
the stop button nothing happens.

... Hope that kinda clears things up about a GUI thread becoming unresponsive.

So what are my options?
I'm thinking that Inovke is basically like SendMessage so maybe somehow i
can replace the windows message loop to do the following, (basically
prioritised message queue)
loop
peek all windows messages and process them, (get/dispatch)
then peek for one of my Inoke calls (get/dispatch)
endloop

Now people that have helped me already may be asking what has as this to do
with windows running in different threads, well the reason I want to do this
is, say for example i have 2 windows in my application, one window is busy
receiving messages from a worker thread (so this is gonna become
unresponsive), i wouldn't like all other windows to become unresponsive too),
switching between windows will require my busy thread to handle some window
messages (loose focus maybe etc) so a prioritised message queue will allow
this, hey maybe this is enough I'll keep at it and see what happens.

But I gues this post comes down to one question,
Is there anyway I can plug into a windows forms message queue and check for
pending invoke calls as described above?

Thanks for any help
Brian.

p.s.
This is only a sample test app, so it's not perfect for many a reason,
I realise the two worker threads calling Invoke is pretty much the same as
One worker thread calling invoke.
clicking close on the forms gets executed straight away for some reason
(maybe it's handled differently?)
Clicking close will throw an exception cause i havn't stopped the worker
thread(s) from sending.

Nov 16 '05 #2
This may not seem like the most helpful of suggestions, but I think it's
pragmatic:

Don't do that!

Specifically, if you find yourself wanting to send messages to the UI thread
hundreds of times a second, that's probably a mistake. It's almost
certainly going to be better in such a situation to have a timer running on
the UI thread that periodically polls to see what has changed, and perform
updates if necessary.

This will solve the priority problem - the System.Windows. Forms.Timer class
uses Win32 windows timers, which send very low priority messages, so your
clicks will always take precedence.

It will also mean the system probably spends less time simply refreshing the
screen - it's always more efficient to do batched display updates than it is
to draw each and every update independently. In naive update
implementations you can find that you've actually spent most of your CPU
cycles repainting stuff, and very little time getting useful work done. The
user can only read updates so fast, so there's not much point trying to
update more than 10 times a second anyway. (Unless you're doing animation -
that's different. But for actual changes of information, even 10 updates a
second is probably more than is necessary.)

In short, sending hundreds (or even tens) of Invoke or BeginInvoke messages
to the UI thread every second is never going to be a useful thing to do.

As to what the *right* thing to do is... Well that depends on what you're
trying to achieve. Polling with a UI thread timer might be a good approach.
Or you might want to use some mechanism for throttling the rate at which you
deliver BeginInvoke calls - never queue up another one until the previous
one has been processed and never deliver them faster than some particular
rate, for example.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

"Brian Keating EI9FXB" wrote:
Hello again,
I've already placed a few posts on this topic.
This time i've a simple application that exhibits my problem,
I've placed sample solution 8k on my website should anyone be interested
in
having a look. http://briankeating.net/transfer/test.zip

To recap the problem I expected (and found).
I've a main GUI thead (main form), this GUI thread has an UpdateTextBox
function that appends a string in a textbox and It also has a button that
stops my worker thread(s) form calling Invoke on main thead.

private void UpdateTextBox(s tring strText)
{
System.Diagnost ics.Debug.Asser t(InvokeRequire d != true, "Invoke was
required", "calling begin invoke not on
the gui thread");
richTextBox1.Fo cus();
richTextBox1.Ap pendText(strTex t);
}

When my form loads I start two worker threads and these threads just loop
around and call Invoke on my main Form with a string to display.

private void ThreadEntryPoin t()
{
while (!bStop)
{
string str = "Thread Id: " + GetHashCode() + ",\t" + nCount.ToString () + "
This is a passing string\r\n";

Invoke(new UpdateTextboxDe legate(UpdateTe xtBox), new object[] {str});
Interlocked.Inc rement(ref nCount);
//Thread.Sleep(10 00); //slow sending
Thread.Sleep(10 ); //fast sending
} //end while

MessageBox.Show (Thread.Current Thread.ToString () + " thread closing");
}

Now if my worker threads are slow sending i.e. I call Thread.Sleep(10 00);
i.e. wait a seond between each invoke call on the gui thread, then I have
no
problem I can click my button and the event handler is called

private void button1_Click(o bject sender, System.EventArg s e)
{
bStop = true;
}

However if my two threads are sending fast (only waiting 10 miliseconds)
then my GUI thread is so busy processing these update events that if i
click
the stop button nothing happens.

... Hope that kinda clears things up about a GUI thread becoming
unresponsive.

So what are my options?
I'm thinking that Inovke is basically like SendMessage so maybe somehow i
can replace the windows message loop to do the following, (basically
prioritised message queue)
loop
peek all windows messages and process them, (get/dispatch)
then peek for one of my Inoke calls (get/dispatch)
endloop

Now people that have helped me already may be asking what has as this to
do
with windows running in different threads, well the reason I want to do
this
is, say for example i have 2 windows in my application, one window is busy
receiving messages from a worker thread (so this is gonna become
unresponsive), i wouldn't like all other windows to become unresponsive
too),
switching between windows will require my busy thread to handle some
window
messages (loose focus maybe etc) so a prioritised message queue will allow
this, hey maybe this is enough I'll keep at it and see what happens.

But I gues this post comes down to one question,
Is there anyway I can plug into a windows forms message queue and check
for
pending invoke calls as described above?

Thanks for any help
Brian.

p.s.
This is only a sample test app, so it's not perfect for many a reason,
I realise the two worker threads calling Invoke is pretty much the same as
One worker thread calling invoke.
clicking close on the forms gets executed straight away for some reason
(maybe it's handled differently?)
Clicking close will throw an exception cause i havn't stopped the worker
thread(s) from sending.

Nov 16 '05 #3
Hi Ian,

What can I say,

1) Thanks a million for spending the time to read that huge post
2) Great suggestion this approach makes a lot of sense.

Thanks again
Brian.

"Ian Griffiths [C# MVP]" wrote:
This may not seem like the most helpful of suggestions, but I think it's
pragmatic:

Don't do that!

Specifically, if you find yourself wanting to send messages to the UI thread
hundreds of times a second, that's probably a mistake. It's almost
certainly going to be better in such a situation to have a timer running on
the UI thread that periodically polls to see what has changed, and perform
updates if necessary.

This will solve the priority problem - the System.Windows. Forms.Timer class
uses Win32 windows timers, which send very low priority messages, so your
clicks will always take precedence.

It will also mean the system probably spends less time simply refreshing the
screen - it's always more efficient to do batched display updates than it is
to draw each and every update independently. In naive update
implementations you can find that you've actually spent most of your CPU
cycles repainting stuff, and very little time getting useful work done. The
user can only read updates so fast, so there's not much point trying to
update more than 10 times a second anyway. (Unless you're doing animation -
that's different. But for actual changes of information, even 10 updates a
second is probably more than is necessary.)

In short, sending hundreds (or even tens) of Invoke or BeginInvoke messages
to the UI thread every second is never going to be a useful thing to do.

As to what the *right* thing to do is... Well that depends on what you're
trying to achieve. Polling with a UI thread timer might be a good approach.
Or you might want to use some mechanism for throttling the rate at which you
deliver BeginInvoke calls - never queue up another one until the previous
one has been processed and never deliver them faster than some particular
rate, for example.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

"Brian Keating EI9FXB" wrote:
Hello again,
I've already placed a few posts on this topic.
This time i've a simple application that exhibits my problem,
I've placed sample solution 8k on my website should anyone be interested
in
having a look. http://briankeating.net/transfer/test.zip

To recap the problem I expected (and found).
I've a main GUI thead (main form), this GUI thread has an UpdateTextBox
function that appends a string in a textbox and It also has a button that
stops my worker thread(s) form calling Invoke on main thead.

private void UpdateTextBox(s tring strText)
{
System.Diagnost ics.Debug.Asser t(InvokeRequire d != true, "Invoke was
required", "calling begin invoke not on
the gui thread");
richTextBox1.Fo cus();
richTextBox1.Ap pendText(strTex t);
}

When my form loads I start two worker threads and these threads just loop
around and call Invoke on my main Form with a string to display.

private void ThreadEntryPoin t()
{
while (!bStop)
{
string str = "Thread Id: " + GetHashCode() + ",\t" + nCount.ToString () + "
This is a passing string\r\n";

Invoke(new UpdateTextboxDe legate(UpdateTe xtBox), new object[] {str});
Interlocked.Inc rement(ref nCount);
//Thread.Sleep(10 00); //slow sending
Thread.Sleep(10 ); //fast sending
} //end while

MessageBox.Show (Thread.Current Thread.ToString () + " thread closing");
}

Now if my worker threads are slow sending i.e. I call Thread.Sleep(10 00);
i.e. wait a seond between each invoke call on the gui thread, then I have
no
problem I can click my button and the event handler is called

private void button1_Click(o bject sender, System.EventArg s e)
{
bStop = true;
}

However if my two threads are sending fast (only waiting 10 miliseconds)
then my GUI thread is so busy processing these update events that if i
click
the stop button nothing happens.

... Hope that kinda clears things up about a GUI thread becoming
unresponsive.

So what are my options?
I'm thinking that Inovke is basically like SendMessage so maybe somehow i
can replace the windows message loop to do the following, (basically
prioritised message queue)
loop
peek all windows messages and process them, (get/dispatch)
then peek for one of my Inoke calls (get/dispatch)
endloop

Now people that have helped me already may be asking what has as this to
do
with windows running in different threads, well the reason I want to do
this
is, say for example i have 2 windows in my application, one window is busy
receiving messages from a worker thread (so this is gonna become
unresponsive), i wouldn't like all other windows to become unresponsive
too),
switching between windows will require my busy thread to handle some
window
messages (loose focus maybe etc) so a prioritised message queue will allow
this, hey maybe this is enough I'll keep at it and see what happens.

But I gues this post comes down to one question,
Is there anyway I can plug into a windows forms message queue and check
for
pending invoke calls as described above?

Thanks for any help
Brian.

p.s.
This is only a sample test app, so it's not perfect for many a reason,
I realise the two worker threads calling Invoke is pretty much the same as
One worker thread calling invoke.
clicking close on the forms gets executed straight away for some reason
(maybe it's handled differently?)
Clicking close will throw an exception cause i havn't stopped the worker
thread(s) from sending.


Nov 16 '05 #4

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

Similar topics

1
1624
by: Codemonkey | last post by:
Hi, Sorry for the cross group post, but I couldn't find a group that deals with threading in .net. Anyway, I've noticed a difference in the way my program acts on Windows 98 than it does on WindowsXP and was wondering if anybody can explain this behaviour. My application runs in the background to collect data through the serial
1
5029
by: Norm | last post by:
I have a program that is cpu intensive so I want to change it's priority to BelowNormal. The code functions without error, the VS Debugger shows the change but when I then go to "Windows Task Manager" and look at my process it still has a "Base Pri" of "Normal". What thing am I missing? C# Code snippet:
6
2562
by: Ayende Rahien | last post by:
Excetremely annoying problem, I've an application with a long startup time. So I created another form with my logo in it to as a splash screen. The splash screen is run from another thread and is communicated solely through static method and Invoke()'s However, when I close my second form, the first one (main window) is hiding under all the windows on the desktop. If I don't close the splash screen, then everything is fine. I tried...
2
2178
by: Miky | last post by:
Hi, I have the following problem: I have a .CFM web page and I have to populate, from VB, two textboxes on it. I was thinking using sendkeys (even if I don't like it too much) but when I open the web browser and navigate to the selected page, I cannot set the focus to the html part of the control (only the web control takes the focus) so I can't use sendkeys to populate the fields I need.
6
2331
by: | last post by:
Just a general question... When working with a form containing a treeview or similar control... if you need to show different form fields depending on what is selected in the treeview then what is the best way to deal with these form controls...? Like, when they are all visible in the designer it can be absolute chaos... So how do you guys deal with it? Is there a blank container control (can't see one) that allows you to drop a...
8
18650
by: Alison | last post by:
Hi, Al I am trying to design a user interface which provides both menus and toolbars for some users to click on whatever they want to do, at the same time, I would like to have a console window available in the same form for users to enter commands and display outputs if some prefer to use character based user interface. I would like to implement the user interface in vb .net. Now I have menus and toolbars ready, but do not now how to get a...
4
2100
by: hzgt9b | last post by:
Using VB .NET 2003, I have a windows application that performs a series of file actions (copy, move, delete) but the actions are completing before the window is painted on the screen... how can I force the form to be painted on the screen first, then the actions start? Or should I pause the app for a few seconds while the form paints. Any suggestion woudl be appreciated!
28
7366
by: | last post by:
I have a multi threaded windows form application that runs great after calling Application.Run(). Application.Run is required for a COM component I a using in the app (required for message loop). I have created a windows service from VStudio 2005 template. What is the windows service replacement for Application.Run()?
0
935
by: theonlydavewilliams | last post by:
Hello. I'm facing a bit of an annoying indecision regarding the design of a particular component of my solution. Perhaps there's someone who can offer some experience/creative insight into it? Here's my scenario: I'm buiding a windows service that calls an xml web service and deals with the responses appropriately. this 'service agent' picks messages from a transactional message queue one at a time, attempts the web call, if it fails,...
0
8667
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9148
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8880
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8853
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6515
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4357
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3034
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
3
1992
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.