I'm currently working on a WPF/C# application which is connected to an external camera. This application gets a snapshot from the camera, then does some analysis and displays it to the screen via a user interface. There are also many other UI elements on the interface (such as buttons, menus, and comboboxes). Right now, while the application is running, the user interface is notably slowed--for instance, a combobox, once clicked, may freeze up for just a second before opening. Then it may freeze again before allowing a user to select a value. I'm pretty sure this is due to the getting of the snapshot happening on the same thread as all the UI, however, I am very naive about using threads properly and really am at a complete loss as how I can go about correctly this issue. Basically, I want the UI to not be noticable slower at all even though the fastest I can retrieve images seems to be about 1 / second from the camera. How could I go about splitting this into multiple threads? AND would that even help my problem any? Thanks so much; any help is deeply appreciated.
If you have access to .NET 4, you could set up a Task to get the snapshot and a continuation to update the GUI. The task will be run on a thread pool thread leaving your UI responsive. Remember to use the FromCurrentSynchronizationContext scheduler for the continuation.
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext;
var task = Task.Factory.StartNew( () => { // Get snapshot })
.ContinueWith(t => { // update ui }, uiScheduler);
If not using .NET 4, you can use the BackgroundWorker.
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) =>
{
// Perform things on the background thread here.
};
worker.RunWorkerCompleted += (s, e) =>
{
// Code to be run after the thread is done, on the UI-thread.
};
worker.RunWorkerAsync();
You Can use background worker , it is nice event based asynchronous mechanism which really does not include user created threads ,though internally uses thread pool . So use it as a starting point.
You can use BGs Dowork event to do CPU incentive task. It supports progress notification so that you can notify ur users about how much work is done.
Only caution has to be taken when updating any ui component, because here you need tdonthink about Dispather.invoke
See more at MSdn.