In my C# Desktop application, I want to show all temporary files in a datagridview but when the datagridview is loading, my program hangs and is not responsive until the datagridview is completely loaded.
How can I make it such that my application is still alive while execution is still going on?
Have a look at using
BackgroundWorker Class
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.
Use BackGroundWorker to Load the grid. It is a separate dedicated thread. Read these articles before implementing
http://www.dotnetperls.com/backgroundworker
http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
Related
I am creating winform to process (convert txt files to tiff) large amount of files. I put all the code behind a button (btnProcess). Is this a good idea? It works but I noticed when I go away from the winform and come back to this I see blank window until the process is complete. I heard about background worker. what is the purpose of background worker?
What you need here is multi-threading. That means that two (or more) threads of code would run in parallel. One of them would be the UI thread, the one responsible for drawing the window. In your case you are running your code in the UI thread and thus blocking the UI rendering while your code is running.
The purpose of the BackgroundWorker is to start an operation on a new thread and is what you need.
BackgroundWorker class
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.
The page I linked above contains a complete BackgroundWorker example.
It depends on your application. If this is a single purpose application that is not extremely long and the only problem is the screen doesn't paint. Which is what it sounds like to me, just throw an Application.DoEvents into the loop and be done with it.
I have a highly multithreaded application , where threads are started from multiple places and i would like to know if i can hook into the running process and just get alerted whenever a new Managed Thread is spawned. I should be able to get the following information
The parent thread
New thread
the method from which the new thread is started like <className>.<methodName>
The application is in C# 3.5
As far as I know there is no way to detect when a thread starts. The best solution is probably not to create thread directly, but instead do it via a "thread manager" class that will raise an event when it starts a thread.
State should be handle within the thread processing logic.
I suggest you create a wrapper class which wraps the thread logic and reports it's status and other items as needed. I created such a class for a multi-threaded application where I could corral the status of the threads and pipe that information to the GUI in a standardized way.
Of course I had the luxury of designing it up front, to which, you may not have.
I am running a C# winform application that shows huge number of statistics and charts frequently. This application consist of multiple forms, each form has different output. When I open the task manager and check out the cpu usage, I find that only one core out of my eight cores is over loaded and the rest are doing nothing!
Is there a way, for example, to assign each number of forms to a core. I need to improve the perfomance.
What I am looking for is to multithread my winforms such that each form would have a different thread that is running on a different core. Is that possible ?
The bottleneck is happening from loading the data into the controls.
It is possible to have multiple UI threads in a single WinForms application. Each UI thread must call Application.Run() and you'd need to mark the entry point to each with [STAThread] just like you do in the Main function.
I have successfully done this and it's a reasonable approach when faced with an existing codebase that's doing too much work on its UI thread. But... I would say this is a symptom of a design that could be improved in other ways. If you're doing too much work on your UI thread think about ways to get that work done on other threads. In my apps I've tried to get all non-trivial work done on non-UI threads. It can be done, but it's not always the fastest way to deliver software.
If doing no other work, a single UI thread is ample to draw 8 screens full of numbers and charts, and update them more frequently than a human can keep up. I know this to be the case :-)
This is technically doable, more flexible in WPF than in WinForms (in my experience), but not recommended in either. Windows client apps tend to run with a single thread responsible for drawing the UI; typically background threads are used for background processing of data access or business logic. Additionally, you'd have to be doing a lot of work in the UI for rendering performance to actually be an issue - this sounds like unnecessary work to me.
However, the basic style in WinForms would be something like this:
var t = new Thread(() =>
{
var f = new Form1();
Application.Run(f);
})
t.Start();
Things you need to be aware of:
you will always have to Invoke calls between forms to make sure they're on the right thread.
if anything in your business layer has thread affinity, you'll need one instance per form that uses it.
application shutdown typically happens in response to the main thread's forms closing. You may need to handle your shutdown manually, though with the code above you have two message loops running and either will keep the app alive when the other's form closes.
Always do data crunching, receiving from I/O, parsing and whatnot on a separate thread or several threads if you need/want.
Then if you're loading a lot of data to UI controls, make sure you don't synchronize with the UI thread too often, like if you invoke every single item from an input stream separately and there are thousands of these per second - WinForms will grind to a halt.
Queue visual data changes in your background thread(s) and batch them to the UI thread with a minimum interval so as to not do this too often - the thread sync is expensive. AddRange is your friend.
I am a beginner with WPF, in my application I need to perform a series of Initialization steps, these take 10-15 seconds to complete during which my UI becomes unresponsive.
I was using yesterday the background worker but it didn't update my window, in fact it was frozen. Not sure, but maybe it didn't work because this control is only for Windows Forms.
UPDATE:
If not too much trouble, can you post me an example to use the alternative? For my case, the program will get some values from a database in a blucle.
Dispatcher.
The Dispatcher maintains a prioritized queue of work items for a specific thread. This might help you for updating your UI. If you have a lot of UI related initializations even this won't be able to help you much.
Dispatcher is not always an alternative to BackgroundWorker actually. The best practice is to select the more appropriate one as per your requirement. For example if you want something to execute without queuing BackgroundWorker is the solution. On the other hand if queuing is not a problem then Dispatcher is an alternative. For example, Dispatcher is using in Spell checkers and syntax highlighting functionality.
WPF Thread Model
All WPF applications start out with two important threads, one for
rendering and one for managing the user interface. The rendering
thread is a hidden thread that runs in the background, so the only
thread that you ordinarily deal with is the UI thread. WPF requires
that most of its objects be tied to the UI thread. This is known as
thread affinity, meaning you can only use a WPF object on the thread
on which it was created. Using it on other threads will cause a
runtime exception to be thrown. Note that the WPF threading model
interoperates well with Win32®-based APIs. This means that WPF can
host or be hosted by any HWND-based API (Windows Forms, Visual Basic®,
MFC, or even Win32).
The thread affinity is handled by the Dispatcher
class, a prioritized message loop for WPF applications. Typically your
WPF projects have a single Dispatcher object (and therefore a single
UI thread) that all user interface work is channeled through.
NOTE :
The main difference between the Dispatcher and other threading methods
is that the Dispatcher is not actually multi-threaded. The Dispatcher
governs the controls, which need a single thread to function properly;
the BeginInvoke method of the Dispatcher queues events for later
execution (depending on priority etc.), but still on the same thread.
See this thread for more information.
You could also queue items up with the thread pool and run the tasks like that, but be careful, if your tasks need to update the UI when they are finished you will have to marshal the data back to the UI thread.
One could use asynchronous delegates.
http://msdn.microsoft.com/en-us/library/ms228963.aspx
Just make sure if you are doing any UI related updates use:
Dispatcher.CheckAccess()
Here a simple example:
private void HandleUIButtons()
{
if (!btnSplit.Dispatcher.CheckAccess())
{
//if here - we are on a different non-UI thread
btnSplit.Dispatcher.BeginInvoke(new Action(HandleUIButtons));
}
else
{
btnSplit.IsEnabled = true; //this is ultimately run on the UI-thread
}
}
Taken from here:
http://blog.clauskonrad.net/2009/03/wpf-invokerequired-dispatchercheckacces.html
My application performs time consuming work independently on several files. I created a BackgroundWorker to pass the work off to on each file, but it appears the backgroundworker is only capable of performing asynchronous work. Is it possible to do several asynchronous tasks in unison with it, or is there a similar object for performing synchronous operations?
The background worker is usually used to update the UI and/or to pass off work so you don't freeze the UI when a long running process takes place. This means that you "pass" the background worker process the "file work" and then use a callback to update the UI(usually) all during which your APP remains responsive.
If the items are independent then you might want to spool up a few threads to split the work. Again, if I am understanding you correctly. If I am then you might want to look at Jon Skeet's threading article.
While you can use the BackgroundWorker, I think you should simply spin off a few threads to do the work. One thread (probably the main thread) will create and start these worker threads and then perform a Join on all the workers in order to wait for processing to complete.
Alternatively, have a look a the Parallel Extensions for .Net if you are using .Net 3.5. The Task object from that library is probably perfect for your situation.
You can do multiple aynchronous tasks by creating more then one BackgroundWorker object in your code. We created a JobPool class that created a number of BackgroundWorker objects to run so that we could control the total number running at any one time. But if there are just a few files you will be processing this wouldbe overkill.