WinForm Application UI Hangs during Long-Running Operation

You need to perform the long running operation on a background thread.

There are several ways of doing this.

  1. You can queue the method call for execution on a thread pool thread (See here):

    ThreadPool.QueueUserWorkItem(new WaitCallback(YourMethod));
    

    In .NET 4.0 you can use the TaskFactory:

    Task.Factory.StartNew(() => YourMethod());
    

    And in .NET 4.5 and later, you can (and should, rather than TaskFactory.StartNew()) use Task.Run():

    Task.Run(() => YourMethod());
    
  2. You could use a BackgroundWorker for more control over the method if you need things like progress updates or notification when it is finished. Drag the a BackgroundWorker control onto your form and attach your method to the dowork event. Then just start the worker when you want to run your method. You can of course create the BackgroundWorker manually from code, just remember that it needs disposing of when you are finished.

  3. Create a totally new thread for your work to happen on. This is the most complex and isn’t necessary unless you need really fine grained control over the thread. See the MSDN page on the Thread class if you want to learn about this.

Remember that with anything threaded, you cannot update the GUI, or change any GUI controls from a background thread. If you want to do anything on the GUI you have to use Invoke (and InvokeRequired) to trigger the method back on the GUI thread. See here.

Leave a Comment