Here's what I'm trying to solve:
My class (which could be hosted by an UI app or a windows service or whatever), needs to receive windows messages. Somewhere around here, someone gave the suggestion (and some source code) to create a windows form in a separate thread that will create the form and whenever a windows message that I'm interested in receives on the WndProc, it triggers a delegate using context.Post.
I've been trying to make it work but unsuccessfully. Instead of spending more time on that avenue and before I try to replicate the problem I'm having there to post here for help, I'm thinking I'm going to try to implement the same solution using BackgroundWorker.
From the tests that I've done, I would expect it to work pretty good when I'm using UIs, but my question is: is there any advice against using BackgroundWorker when not dealing with UIs?
Edit:
The way I'm envisioning it, every time my "child" form (the one running in the background worker) receives a message, I will issue a ReportProgress. The only thing that I need to pass through threads is the message ID, so technically it should suffice right?
BackgroundWorker and a window are water and fire. A window requires an STA thread and a message loop, neither are provided by BGW. Check my answer in this thread for an alternative.
I would say if its at most every 5 seconds, then you should be fine passing the message id (as userState) back via the ReportProgress event.
The BackgroundWorker object is an excellent method of performing the tasks you're looking to perform. You may, however, find that a simple message ID is no longer sufficient when you get things coded up, but the BackgroundWorker.ReportProgress method allows you to pass in a state object. If you code up an efficient state object you can literally send back thorough snapshots to report back to the parent form.
Related
I know there are other questions around this but most end up with the answer don't do what I am about to suggest. So I know you aren't supposed to. The reason for this question is I want to do it anyway, how can I do it...
Here is why I want to break the rules...
Let's say I have a complicated application, it's version 1 and we want our customers to submit errors to us in the event of crashes or hangs. Let's now say I have a button on the top of the main form they click to submit reports.
Let's now imagine that the application hung because of a deadlock...
It would be nice if that small piece of UI and a handler for that button could live on a thread other than the main ui thread so that it isn't caught up in the deadlock. When clicked it would gather all the call stacks for the other threads and submit them to our error reporting service.
Now, knowing the scenario, can this be done in .net?
Yes, there is no magic in creating UI on another thread than the "main thread". The important rule to always keep in mind is to interact with that UI on the thread that created it.
Still, I feel that you are attacking this from the wrong angle. You should probably instead make an effort to push all work off the main thread. That way you minimize the risk for that thread to freeze, and then you don't need to resort to unorthodox solutions for the error reporting.
I have various cases of creating forms on non-main thread, and it works fine every time.
Create a new Thread, and show a Form from it. New message loop will be created for that thread and everything will run fine.
What magic will you use to gather data from the crashed app and locked main thread, that's up to you :)
if application hung, your main message loop is dead, thus ui will not work. As workaround for your problem i'd consider usage of external application (another exe) which will be invoked in case of report
in any case, if you want to invoke UI from other thread you should perform context switch In case of winforms, follow this answer
It sounds like you'd like to keep the UI alive, even when some other operation is mired in a deadlock. If so, perhaps Asynchronous Programming would be of use. Using Async to manage a potentially hung up task would allow the remainder of the application to remain responsive.
we want our customers to submit errors to us in the event of crashes or hangs
You might also consider adding some degree if instrumentation/reporting, so that you'll have this data without requiring user input.
This one is a tough one...
I've got a C# app that runs an HTTP server in a BackgroundWorker, it allows users to input data, that should display in real time onto a main form. The HTTP server basically runs in a do/while(true) loop, that always waits for the HTTP response. So it has to run in a BackgroundWorker so that the program does not stop responding while waiting for the web user. However, when the user enters data, I want the background worker to update the data on the main form.
I've tried making the functions of the main form public, but this gives a run time exception because the thread accessing the forms controls is not the thread that created them.
I've thought about just using the ProgressChanged event of the BW, but I've got to pass a lot of data, and it would be nicer to pass more than just a string. Can I override this method, and if I can, how/where would I do it??
Thanks.
Go ahead and use ProgressChanged as-is. It doesn't really matter how big the object you're passing as the userState parameter is, as long as:
It's a reference type (that is, not a struct).
The background process doesn't modify its contents after passing back to the main thread, to avoid a race condition.
I have a C# app that receives updates from a server, processes it, and updates the GUI. the updates come in constantly, say several times a second. I want the app to update the GUI at most once every 2 seconds. so if an update comes in at time T, I want all updates that come in from T through T+2sec to stay in a buffer, and at T+2sec do the processing and GUI update. I know in JS you can use setTimeout() to execute some code at some time in the future, so I want something like that.
what's an appropriate way to do this? I've heard that using threads to "schedule" a function call isn't a great idea, but I'm not sure of a better way to do this. would it be so bad to use a Timer with a two second interval, synchronized to the GUI thread, that does the processing/updating?
You can use a System.Windows.Forms.Timer. It doesn't run events in a separate thread, it's the GUI thread that runs them. That way you can update the GUI directly without having to use Invoke.
You should use one of the timer classes, as you posted in your question.
See this MSDN article comparing them - this should give you a good basis to make a decision.
Could you please tell me how do I go about pausing my program for 500 milliseconds and then continue?
I read Thread.Sleep(500) is not good as it holds up the GUI thread.
Using a timer it fires a callback ...
I just want to wait 500ms and then continue to the next statement.
Please advise.
EDIT: I need to display a status bar message for 500ms and then update the message with a different one. Sorry, I meant 500 not 50.
EDIT: I do understand what all you have said. but: [I just want to wait 500ms and then continue to the next statement.] I think because it is such a short interval i am going do a Thread.Sleep(500) on the main GUI thread. Otherwise i would have to rewrite a lot of code to accomodate this brief interval of 500 milliseconds.
EDIT: i will try to reformat my status message so the pause is not needed.
Hmya, what you're trying to do is pretty fundamentally incompatible with the Windows programming model. A native Windows program is event driven. Your program is always idle, sitting inside a loop started by Application.Run(), waiting for Windows to tell it that something interesting happened that it should respond to. Paint requests, mouse clicks, timer expirations, stuff like that.
Your program should respond to this and filter what is interesting to you. When you drop a button on a form, you are always interested in the Click event, generated when Windows sends the MouseDown notification message. Your Click event handler runs some kind of custom code that you write. Like updating a status bar message in your case.
Updating the status bar message half a second later doesn't make a whole heckofalot of sense. What exactly happened during those 500 milliseconds that changed the way your program responds to events? You can call the Update() method of the StatusBar so the new message is visible, then call System.Threading.Thread.Sleep(500) to get what you want. You'll get away with it, the "Not Responding" ghost that Windows puts up takes your program going dead for several seconds.
But that doesn't make a lot of sense, nothing happened during that half second, the state of your program didn't change. It couldn't change, it was dead to Windows and not receiving any messages that would allow it to change state.
Well, that's about as far as I can take this. Please update your question and explain why you need to do this. Just in case: if you're contemplating this to fake doing something important for half a second, your user will not be impressed. She'll eventually notice your UI is dead for half a second without anything to show for it.
You have two choices:
Use a timer as you suggested. Split your method up into two methods, foo1 and foo2. Use the foo1 to start the timer and run foo2 in the callback.
Use a BackgroundWorker for running the entire function and use Thread.Sleep on the worker thread.
From your update it seems that the only thing you want to do is change a single field. I would definitely recommend the first method: using a timer. Starting a BackgroundWorker for this task is overkill and will just give you unnecessary extra work and complications.
Instead of pausing the UI directly for 500 ms, you can always use a BackgroundWorker. That will cause your callback to run in a separate thread, where you can use Thread.Sleep to pause it without blocking the UI. Then when you are done, just update the status bar with your new message.
More context to the question would be helpful.
Thread.Sleep(50) will pause the current thread for 50 milliseconds. If you're doing this in the UI thread, then yes, it will freeze the UI for 50 milliseconds. However, if you use a different thread to do this processing, then calling Sleep on that thread will pause it for 50 milliseconds without freezing your UI thread.
See Marc's answer to this question for an example on using a BackgroundWorker instance to do what you need.
In C# your best bet is to use the Timer and fire a callback.
In F# there is an awesome way to do what you want, see
F# async on the client side
which shows how to write straight-line code and have the language take care of the callbacks for you.
You need to allocate another thread. In that thread you Sleep(500) and change the needed data. Caution: you would need to use the original thread's dispatcher, because the data related to UI should be usually updated from the GUI thread.
I have a problem with interface lag in C#.
Since I'm still learning please be patient whilst I explain.
I have narrowed the problem to my timer object.
Basically my program queries a device through TCP/IP socket and outputs it to a textbox on screen.
Now I am polling the device for data every second which requires some logic to be buried within timer object and the following is what happens between ticks:
Increment a value.
Construct the 2 strings that represents the command to be sent to
the box (encapsulated in a function
Encode the command
Send command
Clear the byte array
Receive reply.
Could this be too much processing being done in the event handler? Every time I try to move the window during the polling session i.e. when the timer is running I get a very bad input lag.
The timer you are using is executing on the windows message thread. Therefore, while the polling is running the windows message queue is blocked. This isn't a problem with doing too much processing, most of the time the thread will be waiting for the TCP/IP response.
To fix this, you just have to do the do the work on a background thread and then update the UI on the UI thread.
There are a heap of different timers in the .NET framework that work in different ways, the one you are using works processed the timer event on the same thread, others work on background threads. Check this article out about the different timers.
You could also just use your current timer to invoke a BackgroundWorker component to do the work on the background thread. The main benefit of this is the the BackgroundWorker will do the work on a background thread, but will raise the work complete event on the UI thread so that it is simple to update the UI without having to worry about which thread you are on.
I think this is because you're trying to do work in your UI thread. Have your timer run in a background work thread.
It seems like there are a few things going on. First, you may be doing too much in your timer tick handler. How are you constructing the string and encoding the command? Can any of this be done once outside the tick handler or simplified in any way (using String.Format calls, for instance)? There are actually three different timers available in .NET, with different resolutions. Which timer are you using?
The biggest issue is the fact that your interval is 1 second. No matter what, that is a lot of processing overhead. Keep in mind that, for the most part, every time the interval is hit and the tick handler is invoked you are causing a context switch between threads. There is a bit of overhead involved in this (nothing which you can do anything about) and the more often you context switch the slower your performance appears.