1

Is there a library/framework to execute long running actions in .NET? Looking for something like this:

private void button1_Click(...)
{
  LongActionRunner.Execute((ref int total, ref int done) => {
    // i know it's not thread-safe
    total = 100;
    for(var i = 0; i <= 100; ++i) {
      done = i;
      Thread.Sleep(100); // slow
    }
  });
}

When Execute() is called, I need to display a window with progress bar. If my action throws, it should display an error message, etc.

Are there any existing solutions?

Andrey Agibalov
  • 7,624
  • 8
  • 66
  • 111

2 Answers2

3

You can use the BackgroundWorker. It is meant especially for the scenario that you presented. See here for a tutorial on how to implement a progress bar using BackgroundWorker.

Community
  • 1
  • 1
jle
  • 9,316
  • 5
  • 48
  • 67
0

BackroundWorker uses a thread pool thread, so you should only use it for relatively ( 1 second max ) units of work. If your operation is going to take longer than that, you should create a thread.

I, along with many others I suspect, have written this for commercial projects, but I don't know of any open source solution. I agree you need to display a dialog with a progress bar, if only to prevent the user pressing button1 twice and causing re-entrancy. As you say, you also have to handle errors and cancellation.

Nick Butler
  • 24,045
  • 4
  • 49
  • 70
  • Could you provide a citation for the "1 second max" claim? I have been using BackgroundWorkers that take many hours in commercial projects for many years without problems. – Dour High Arch Oct 07 '11 at 22:33
  • @Dour: Here's a previous question: http://stackoverflow.com/questions/230003/thread-vs-threadpool Using the thread pool for long-running tasks confuses its thread management algorithms – Nick Butler Oct 08 '11 at 07:53