GUI freezes during execution - c#

I have developed a GUI to capture packet via ethernet cable.
For this purpose i have 3 separate functions I am running each function in separate thread.
1) public void Capture_Click(object sender, EventArgs e) //packet capturing
2) public static void PacketHandler(Packet packet) // storing received packets and showing in dataGrid
3) public void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e) // I have Kept a button on each row to get packet details in more detail.
Problem: When packets are coming that there is no problem but as soon as packet stop coming GUI freezes now I am not able to click Detail button in DataGrid.
suggest possible solution?

It seems you are receiving (psychic debugging) packages in your ui thread. A solution could be to do this in a background worker. This will allow your ui to update and receive/handle your incoming packages at the same time.
MSDN Backgroundworker
From MSDN: The BackgroundWorker class allows you to run an operation on a
separate, dedicated thread. Time-consuming operations like downloads
and database transactions can cause your user interface (UI) to seem
as though it has stopped responding while they are running. When you
want a responsive UI and you are faced with long delays associated
with such operations, the BackgroundWorker class provides a convenient
solution.

Related

http request button. destination unreachable

In c#,
I have a device that accepts HTTP requests as remote commands.
I've created a button that send those requests, it's not the perfect but it works.
However, when the device is disconnected and there is
destination unreachable
response the application freezes until i restarts it.
I need a way around it, maybe some timeout that will close the stream after 1 second.
private void httpBTN_Click(object sender, EventArgs e)
{
String URI = "http://192.168.1.118/cgi-bin/aw_cam?cmd=DCB:0&res=0";
WebClient webClient = new WebClient();
Stream stream = webClient.OpenRead(URI);
stream.Close();
}
Long running operations in GUI's are propblem: As long as the operation has not finished (result or timeout), the event does not finish. And as long as a Event does not finish, no other code can run. Not even the code that updates the GUI with changes or "yes, I got the message about a user input" to Windows. You will need some form of Multitasking.
Luckily Networking is one of the most common cases of long running Operations, so it has build-in ways of multitasking (the async functions). However that might no be the best start. As Multitasking beginner I would advise towards using the BackgroundWorker in Windows Forms. At least until you got a handle on Invoke and Race Conditions. async/await is the better pattern longterm, but has a much steeper learning curve.

How to handle a background thread when the app gets deactivated

I am using a background thread to make an async call to the web service and return the results.When the background thread is running and my app gets deactivated, say the user presses the home button, How do I handle it?
private async void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
//What should I do here?
}
I understand from the following blog http://www.wintellect.com/blogs/jgarland/proceed-with-caution---windows-phone-8-app-lifecycle-events-vs-async-methods that I cannot await till the background threads complete in the deactivated method.Also it suggests using synchronous calls.In case I have to cancel my background thread inside deactivated event,How do I find which background thread is running at the moment?In every page where web service is called , a background thread is used.Is there any way to resume a background thread after app is activated again?
You are right that when your App is deactivated then all processes are stopped - MSDN source:
When the user navigates forward, away from an app, after the Deactivated event is raised, the operating system will attempt to put the app into a dormant state. In this state, all of the application’s threads are stopped and no processing takes place, but the application remains intact in memory.
In your deactivated event you should invoke Cancel request to all your background threads. If you are using aync-await then you can equip those methods with CancellationTokenSource. Here is some more about this: Enabling Progress and Cancellation in Async, Cancel an Async Task or a List of Tasks , and you can find lot of information on Stephen Cleary blog.
As for the question to know which Task is running I think you can use this CancellationTokenSource to check it - if it isn't null then it means that your bacground thread is working.
And as for reacivating your method - everything depends on your code and what that method perform. If you are downloading a group of files then you can remember which are downloaded and after activation call method downloading the rest. If you perform some calculation then you can remember the place where the method stopped and try to resume further calculations. Thought it can be sometimes hard. And you must remember that you have limited time to 10 seconds:
You should not wait until the Deactivated event occurs to store this data. Remember that all application lifecycle events enforce a limit of 10 seconds for an application to complete any tasks.
About other possibilities:
If you want to perform some actions in background proces - then you can use Background agents and Background transfers if you want to download a file. There is also Background audio, but I suppose you are not asking about it.
If you want your app to stay in foreground when lock screen is engaged then you can Deactivate Idle Detection.

How to make 2 forms on 2 separate threads in C# winform application

I am developing an interface in my C# 4.0 winform application, to fire some sms in bulk. Each message content is different so that I have to fire messages one by one. I have a form from where the end user can shoot smss, it may be more than a thousand.
I want to manage a queue. If the user shoots a sms then it will be submitted to the queue and the queue will send sms one by one.
So I have to create a form to manage the queue. The problem is that I want my application to work normally and in the background the queue sends sms.
So how can I achieve this task? I have tried BackGroundWorker, but I don't know how to maintain a separate thread with a form.
All forms must be on the UI thread. The sending of the SMS should be performed by the BackgroundWorker.DoWork event. The updating of the form is then done by BackgroundWorker.RunWorkerCompleted event.
The UI thread is main thread of the application for SWF (winforms)
If you are using C# 4.0 or above, you may also want to investiage the Take Parallel Library (http://msdn.microsoft.com/en-us/library/dd460717.aspx). But I would first get BackgroundWorker implementation to work. Then use TPL to send simultaneous SMS. Could really speed things up.
you have to create one thread (called worker thread) which runs for the life your application.
you have to have a queue or even better a concurrent queue http://msdn.microsoft.com/en-us/library/dd267265.aspx
the worker thread wait when an item (sms) appears in the queue, takes that item and do its work.
the UI is completely decoupled from that work.
this is most basic use of the class Thread.
Background worker is least suitable solution. obviously you can use a washing machines to build a house but most people use bricks.
You can start Thread then create new instance of form on it (with no parent) and then start message loop (such code located in Main method of project's template).
Remember, any form (generally any GDI object) can be used only on thread that creates it. E.g you can't create child form on another thread, then parent's. Every GUI thread must run message loop.

C# Wait for async operation to finish

I'm wondering what the best approach might be for what I'm trying to do. My application has a button that starts a background download operation, and then performs some actions dependent on the downloaded files.
It's like a "The game will begin shortly once necessary data is downloaded" situation, where the user may still use the main form.
private void btnStart_Click(object sender, EventArgs e)
{
//execute some code
Downloader.RunWorkerAsync(files); //this worker reports progress to the main form
while (Downloader.IsBusy)
Application.DoEvents();
//execute some more code
}
I'm aware that doing it that way is not good at all.
I cannot execute the download code synchronously, because the main form needs to remain responsive during the download operation.
I also cannot put the final code into the download completed event, as it is used by many other areas of the program and must remain a "generic" download system.
So, is there a way to do what I want? I do not have any experience with other async methods.
If you use BackgrounWorker you must configure it properly. BW has RunWorkerCompleted event to which you must subscribe to handle completion of you async work.
I think you should use asynchronous programming features of the .net 4.5 framework (await and async).
refer to async programming

call a function after function finish

first time poster here!
I'm a Senior Computer Science Student and I'm currently developing a GUI that plays A board game (othello ) online using telnet.
the pseudo is something like this...
click button
update GUI
recieve telnet input
update GUI
rinse and repeat!
the problem is though, the only way i know how get the telnet function to go is by putting it inside the Click event handler, but the GUI won't update until the whole function is finished. Meaning it updates every two moves instead of one. Is there a way to tell C# ( which I'm new to) to call a new function immediatly after one has finished? specifically on a GUI.
any input is appreciated
Thanks
I'm not sure I understood correctly the problem, but the "receive telnet input" line makes me worry a lot.
Are you writing this application in a single thread without using any kind of asynchronous TCP/IP communication?
If the answer is yes, the error is in the architecture you are using.
You need asynchronous tcp/ip communication, for example, with another thread running in parallel, with asynchronous sockets or with asynchronous streams.
You cannot stop the GUI waiting for the network, it would be a bad architecture.
Try to read this simple but complete article on codeproject: http://www.codeproject.com/KB/IP/socketsincs.aspx
Windows OS uses a thing called "message pump" to handle windows. Everything is a message that is processed by a single thread (your application thread).
Events are enqueued in the message queue.
If you stop the execution of the main thread for too long you are stopping the message queue from being processed, and this will stop user input and also painting, since rendering is also a windows message that can be enqueued.
You'll need to use threads. This way while one thread is still processing you can fire off a new thread. I think that's the only way you'll be able to simultaneously finish processing one task while starting up another at the same time.
Once the task is done processing you can join it back to main thread.

Categories

Resources