Reputation: 3854
I have a C# WPF application which does some data processing.. Since the application takes some time to do the processing, sometimes the window freezes. So I am basically trying to find a way so the user doesnt freak out.. I was thinking of producing a second window when the processing is going on with some stats while the main window stays either in background or hidden until the processing is completed whichever works better. Maybe that will prevent things from freezing up or atleast hide it?
At the moment, I tried creating a second window when the processing starts by using the following code... but I am not sure how I would edit the XAML for it. I'm using VS 2013 and only see the XAML for my initial window. Any help will be appreciated!
Window win = new Window();
win.Show();
win.Activate();
Upvotes: 0
Views: 3335
Reputation: 1208
The issue you're running into is that you have the UI thread trying to do all of the work. While the UI thread is working on a long term process, it isn't able to update your window.
What you want to do is let a separate thread handle the background process. This works well until the user wants to close the windows or cancel the current process. That's when you have to start worrying about the interactions between the UI thread and worker thread. To do this .Net gives us something called a cancellation token, that will allow us (if we wanted) to manually keep track of when to cancel a process.
The Cancellation Token is easily used with the Task class. You can complement this with the await/async so you don't have to manually check to wait on the completion of the task.
Your options will vary based on your current Framework.
Upvotes: 0
Reputation: 611
The last time I worked in WPF, i don't think it can handle multiple windows very well. Even so, it wouldn't solve your problem. Your problem is that your long running task is running on the same thread as your UI.
The true solution to your problem is Asynchronous coding. For background info, check out the .net TPL, as well as async/await features. These are available in .net 4.0 and 4.5 ,respectively.
Here's an example of how you would use it.
private async void BeginProcessingAsync(Data d)
{
//Show to user that task is running
this.IsLoading = true; // Show a loading icon or something.
//Execute the long running task asynchronously
await Task.Run(() => LongRunningMethod(d));
//Anything after the await line will be executed only after the task is finished.
this.IsLoading = false;
DoSomethingWithFinishedData(d);
}
Upvotes: 6
Reputation: 24385
You should run your long-running processing on a different thread or in the background.
One easy way to do this is with a BackgroundWorker
var bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
//put the long running process in here.
};
bw.RunWorkerAsync();
Upvotes: 2