473,698 Members | 2,261 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can i implement a message pump with winforms ?

Hi all,

i'm doing a quite long treatment in a function, and i'm showing the
progress of the treatment with a progressbar. The code is something
like this :

for each(entry in entries) // about 100 entries
{
TreatmentForOne Or2Secs();
this->progressBar1->PerformStep( );
}
during the debug, the debugger tells me that :

Managed Debugging Assistant 'ContextSwitchD eadlock' has detected a
problem in 'd:\test\NetSen dDotNet\debug\N etSendDotNet.ex e'.
Additional Information: The CLR has been unable to transition from COM
context 0x189558 to COM context 0x189408 for 60 seconds. The thread
that owns the destination context/apartment is most likely either doing
a non pumping wait or processing a very long running operation without
pumping Windows messages. This situation generally has a negative
performance impact and may even lead to the application becoming non
responsive or memory usage accumulating continually over time. To avoid
this problem, all single threaded apartment (STA) threads should use
pumping wait primitives (such as CoWaitForMultip leHandles) and
routinely pump messages during long running operations.
Specially :
To avoid this problem, all single threaded apartment (STA) threads
should use pumping wait primitives (such as CoWaitForMultip leHandles)
and routinely pump messages during long running operations.

So, how can i pumping messages ? or, should i use a thread (and how ?)
Thanks for your help
Nicolas H.

Feb 13 '06
17 23703
ok, i've tried this, but this is not working, as if the window is
frozen

I'm using ThreadPool and ManualResetEven t in my form class

Is this way of doing not good ?
System::Collect ions::ArrayList ^ getList()
{
list = gcnew System::Collect ions::ArrayList ();
manualEvent = gcnew System::Threadi ng::ManualReset Event(false);
System::Threadi ng::ThreadPool: :QueueUserWorkI tem(gcnew
System::Threadi ng::WaitCallbac k(this,
&myNameSpace::f rm_loading::Thr eadProcess));
manualEvent->WaitOne();
return list;
}

void ThreadProcess(S ystem::Object ^ stateInfo)
{
manualEvent->Reset();

this->progressBar1->Minimum = 0;
this->progressBar1->Maximum = nb;
this->progressBar1->Value = 0;
this->progressBar1->Step = 1;
this->Show();
this->Update();

for each (entry in entries)
{
TreatmentLongOn Entry();
this->progressBar1->PerformStep( );
}
this->Hide();
manualEvent->Set();
}
How can i correct ?

Thanks in advance

Best regards,

Nicolas

Feb 13 '06 #11

<ni************ *@motorola.com> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.com...
| >That means you are running your long running task on the UI thread, this
is
| >something you should not do, run this on another thread and call Invoke
or
| >BeginInvoke to update the progressBar, that way your UI will remain
| >responsive.
|
| Yes, i'm running the task on the form class.
|
| So, i'm going to use thread ... but, i just need something easy
|
| something like this
|
| Thread ^ t = gcnew Thread(gcnew ThreadStart(Thr eadProcess));
| t->Start();
| WaitForTheThrea dToTerminate();
|
| Is this possible ? and how ?
|
|
| Thanks for your help
|
I would suggest you take some time to read the docs before you start using
multiple threads.
Anyway here is how you could init a background thread, probaly you must
initialize him to enter the STA as you seem to call into COM in your "task".

// in some handler (button click ??)

Thread ^ t = gcnew Thread(gcnew ThreadStart(thi s->MyLongRunningT ask));
t.SetApartmentS tate = ApartmentState. STA; // see above
t.IsBackground = true;
t->Start();
// no need to wait for the thread to terminate!!
....
void MyLongRunningTa sk()
{
// keep the busy

}
Willy.
Feb 13 '06 #12
>I would suggest you take some time to read the docs before you start using
multiple threads.
Anyway here is how you could init a background thread, probaly you must
initialize him to enter the STA as you seem to call into COM in your "task". // in some handler (button click ??) Thread ^ t = gcnew Thread(gcnew ThreadStart(thi s->MyLongRunningT ask));
t.SetApartmentS tate = ApartmentState. STA; // see above
t.IsBackground = true;
t->Start();
// no need to wait for the thread to terminate!!
... void MyLongRunningTa sk()
{
// keep the busy

}


Thanks for your help,

In fact, i need to wait for the thread to finish, because, as you can
see in my last post, i'm returning a list, that is built in the
longTask function.

Regards

Feb 13 '06 #13

<ni************ *@motorola.com> wrote in message
news:11******** *************@g 43g2000cwa.goog legroups.com...
| >I would suggest you take some time to read the docs before you start
using
| >multiple threads.
| >Anyway here is how you could init a background thread, probaly you must
| >initialize him to enter the STA as you seem to call into COM in your
"task".
|
| >// in some handler (button click ??)
|
| > Thread ^ t = gcnew Thread(gcnew ThreadStart(thi s->MyLongRunningT ask));
| > t.SetApartmentS tate = ApartmentState. STA; // see above
| > t.IsBackground = true;
| > t->Start();
| >// no need to wait for the thread to terminate!!
| >...
|
| >void MyLongRunningTa sk()
| >{
| >// keep the busy
| >
| >}
|
| Thanks for your help,
|
| In fact, i need to wait for the thread to finish, because, as you can
| see in my last post, i'm returning a list, that is built in the
| longTask function.
|
| Regards
|

No, Waiting on a UI thread means rendering the UI non-responsive. I guess
you need the list to update the UI, well do this from the non UI thread
using Control->Invoke or BeginInvoke.

Willy.
Feb 13 '06 #14
>No, Waiting on a UI thread means rendering the UI non-responsive. I guess
you need the list to update the UI, well do this from the non UI thread
using Control->Invoke or BeginInvoke.


Hi again and thanks for your answer. I tryed to implement the method
using BeginInvoke. But, the UI is still quite frozen (my progressbar is
refreshing, but the entire form is not). And when i put an other
application on top of the z-order, i can't go back to my window, during
the long task.

This is my code, i hope you can find why it's not working (I'm calling
the method getList(), that constructs a list, shows a form with a
progress bar during the construction, and returns me the list at the
end)
System::Collect ions::ArrayList ^ getList ()
{
list = gcnew System::Collect ions::ArrayList ();
int nb = 40;
this->progressBar1->Visible = true;
this->progressBar1->Minimum = 0;
this->progressBar1->Maximum = nb;
this->progressBar1->Value = 0;
this->progressBar1->Step = 1;
this->Show();
this->Update();
System::IAsyncR esult ^ res;

res = this->BeginInvoke(gc new InvokeMethod(th is,
&myProject::frm _loading::Updat eProgressBar), nullptr);
this->EndInvoke(res) ;
System::Threadi ng::Thread::Sle ep(1000);
this->Hide();

return list;
}

private:
void UpdateProgressB ar(void)
{

for (int i=0;i<40;i++)
{
list->Add(System::Co nvert::ToString (i));
this->progressBar1->PerformStep( );
System::Threadi ng::Thread::Sle ep(500);
}

}
Thanks a lot in advance

Feb 14 '06 #15
I don't see any thread creation in the code you posted, is getList() your
thread procedure?
Also, you don't need to call EndInvoke after a BeginInvoke call. I also
don't get why you are calling Sleep either.

Willy.
<ni************ *@motorola.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
| >No, Waiting on a UI thread means rendering the UI non-responsive. I guess
| >you need the list to update the UI, well do this from the non UI thread
| >using Control->Invoke or BeginInvoke.
|
| Hi again and thanks for your answer. I tryed to implement the method
| using BeginInvoke. But, the UI is still quite frozen (my progressbar is
| refreshing, but the entire form is not). And when i put an other
| application on top of the z-order, i can't go back to my window, during
| the long task.
|
| This is my code, i hope you can find why it's not working (I'm calling
| the method getList(), that constructs a list, shows a form with a
| progress bar during the construction, and returns me the list at the
| end)
|
|
| System::Collect ions::ArrayList ^ getList ()
| {
| list = gcnew System::Collect ions::ArrayList ();
| int nb = 40;
| this->progressBar1->Visible = true;
| this->progressBar1->Minimum = 0;
| this->progressBar1->Maximum = nb;
| this->progressBar1->Value = 0;
| this->progressBar1->Step = 1;
| this->Show();
| this->Update();
| System::IAsyncR esult ^ res;
|
| res = this->BeginInvoke(gc new InvokeMethod(th is,
| &myProject::frm _loading::Updat eProgressBar), nullptr);
| this->EndInvoke(res) ;
| System::Threadi ng::Thread::Sle ep(1000);
| this->Hide();
|
| return list;
| }
|
| private:
| void UpdateProgressB ar(void)
| {
|
| for (int i=0;i<40;i++)
| {
| list->Add(System::Co nvert::ToString (i));
| this->progressBar1->PerformStep( );
| System::Threadi ng::Thread::Sle ep(500);
| }
|
| }
|
|
| Thanks a lot in advance
|
Feb 14 '06 #16
>I don't see any thread creation in the code you posted, is getList() your
thread procedure?
Also, you don't need to call EndInvoke after a BeginInvoke call. I also
don't get why you are calling Sleep either. Willy.


Thanks again for helping me Willy,

I finally changed my way of doing this.

I use the ability of a form to be modal (by calling ShowDialog instead
of Show), then i don't have to care about waiting for the end of the
task.

I'm doing the init in the form_load, then i start a thread, that
perform the long task and update the UI.

At the end of the thread, i'm calling the method close() of the form,
then i came back just after the ShowDialog and i'm getting the list
from the form.
I suppose i can do this, because i didn't dispose the ressources of the
form, right ?
This is now working,
thanks a lot for your help.
Best regards,
Nicolas

Feb 14 '06 #17

ni************* @motorola.com wrote:
*>I don't see any thread creation in the code you posted, is
getList() your
thread procedure?
Also, you don't need to call EndInvoke after a BeginInvoke call. I
also
don't get why you are calling Sleep either.
Willy.

Thanks again for helping me Willy,

I finally changed my way of doing this.

I use the ability of a form to be modal (by calling ShowDialog
instead
of Show), then i don't have to care about waiting for the end of the
task.

I'm doing the init in the form_load, then i start a thread, that
perform the long task and update the UI.

At the end of the thread, i'm calling the method close() of the
form,
then i came back just after the ShowDialog and i'm getting the list
from the form.
I suppose i can do this, because i didn't dispose the ressources of
the
form, right ?
This is now working,
thanks a lot for your help.
Best regards,
Nicolas *
I know this is old but it came up in my googling and figured I would
finish it off in case anyone reads it and doesn't understand.

I think the OP is missing the concept of not blocking a UI thread. I
will try to straighten it out.

When you register for a UI event, such as a button's click event, you
don't want to do any operations that are long, and you don't want to
block(sleep,pau se, wait) in that function. The reason is that this
callback was performed on the UI's main thread and the UI will not
respond during this time. Instead you should create a worker thread.
I will post some code below, it will be in C# since that is my most
familiar language.
Code:
--------------------
public void OnButtonClick( object sender, EventArgs args )
{
Thread.Sleep( 10000 ); <---- BAD, Blocking UI thread
SuperLongCPUInt ensiveCall(); <---- BAD, Blocking UI thread
}
--------------------
The above is bad, and will block UI events. Instead you should create
a call that will run on a thread in the background.
Code:
--------------------
public void OnButtonClick( object sender, EventArgs args )
{
new Thread( SuperLongCPUInt ensiveCall() ).Start();
}
--------------------
The OP was doing the following.
Code:
--------------------
public void OnButtonClick( object sender, EventArgs args )
{
new Thread( SuperLongCPUInt ensiveCall() ).Start();
manualEvent.Wai tOne();
}

public void SuperLongCPUInt ensiveCall()
{
manualEvent.Res et();
// DO A TON OF WORK
manualEvent.Set ();
}
--------------------
That is the same as making the call on the UI thread, actually it is
slower, you are still blocking the UI thread. If you have to define an
additional function that will be started on a background thread then do
it, just don't ever do CPU intensive or blocking calls on a UI thread.

--
taylorjonl
------------------------------------------------------------------------
Posted via http://www.codecomments.com
------------------------------------------------------------------------

Nov 17 '06 #18

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

Similar topics

2
6905
by: Cantankerous Old Git | last post by:
I am trying to write a program that I hope to get working as a command-line app to start with, and then eventually use a windows service wrapper to call it as a service. Its purpose is to attach to an already running (not ours) service using an API DLL, where it will do houskeeping and monitoring tasks. This is where it all gets strange. Although I can make calls into the API and do things proactively, when I register a callback for...
2
1405
by: Ken Williams | last post by:
Hi I have a DLL written in C/C++ that is passed Hwnd when it is called. When the DLL has data for the calling program it uses Hwnd to post a windows message back to the calling program saying it wants attention. I have looked at Delegates and events, but it's not obvious how I can replicate this feature in C#. Anyone got a sample of code that does something similar in C# ?
2
1831
by: qushui_chen | last post by:
Now i was writing a programe,profile as first==>search data from SqlServer====>send mail to User==>write to log How can i do to implement the multi-thread? thank
3
2847
by: Andrew Baker | last post by:
OK this has me perplexed, puzzled and bamboozled! I have a remoting service which I displayed a message box in. I then wondered what would happen if a client made a call to the service while the message box was being displayed. Since the call comes in on a different thread the client call was not blocked. This seemed to make sense to me. Next I thought, what will happen when the client calls into the server if I try to use a delegate...
6
20078
by: orekin | last post by:
Hi There I have been trying to come to grips with Application.Run(), Application.Exit() and the Message Pump and I would really appreciate some feedback on the following questions .. There are quite a few words in this post but the questions are actually quite similar and should be fairly quick to answer ... (1) What is Happening with the Threads
4
9605
by: yaron | last post by:
Hi, I am developing an infrastructure dll in c#. my dll can be use by all kind of application containers win/web/console. how do i implement a shutdown hook which will be called when the user exit from the application (for all kind of .NET applications)? for example in c# console application i do this with win32 interop SetConsoleCtrlHandler function, but how do i know what kind of application loaded my dll.
3
2316
by: alex | last post by:
I want to implement an async-function,just like Oracle OCI function: for example: I call oci "execute(strSQL)" function, and I can call "cancle" function to cancle the process if the SQL execute too long. How to implement the execute and cancle functions? thx!
5
2093
by: DC | last post by:
Hi, I need the functionality to take a workitem from a stack, execute it in a different thread, get the next item, execute it asynchronously too, and so on. But: there should never be more than 5 threads processing workitems. As soon as the number of threads gets below five, more workitems can be queued. This goes on until the stack of workitems is fully processed. Not sure if that is what one would call a "Thread Pump".
3
1498
by: Luqman | last post by:
How to implement Role Enabled Security in Visual Basic 2005 Windows Application, like we do in ASP.Net 2.0 ? I want to use Sql Server Membership Security for Adding Roles and Users. Can I use system.web.security in Windows Application for this purpose ? Best Regards, Luqman
0
8680
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
9030
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8899
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
5861
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
4371
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...
0
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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
2
2335
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.