views:

160

answers:

7

I have a C# Windows application that does many tasks. some of these tasks are very time wasting. When I run these type of tasks, the other parts of my application will be disabled.

How can I write my application to avoid this? Is using threads a good solution? Is it safe?

A: 

Try using BackgroundWorker

Create a BackGroundWorker (available at the toolbox)

Create the DoWork event (you can access this one in the event tab of the BGW properties)

    private void BGWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        DoTimeConsumingTask();
    }

and call it with the following:

BGWorker.RunWorkerAsync();

You can pass a variable to the DoWork handler, which could be accessed throug

e.Argument //(It comes as an Object, you can use int.Parse, .ToString() or whatever
MarceloRamires
+3  A: 

A first thing you could try is using the BackgroundWorker.

Example

You might have this method that takes a lot of time to run: void HeavyLifting()

So to delegate some work use a BackgroundWorker!

var worker = new BackgroundWorker();

worker.DoWork += new DoWorkEventHandler(someHeavyWork);

The event method someHeavyWork just calls HeavyLifting in this case.

To start the worker simply do this:

worker.RunWorkAsync();

Tip: Updating the GUI Thread

Remember that if you are going to change things in the GUI-thread through this thread, you need to use invoke/delegates for that. You can read about this on MSDN: How can I update my user interface from a thread that did not create it?

Filip Ekberg
Hm why was this downvoted?
Filip Ekberg
+1  A: 

You've had the background worker suggested. The other way is to start a new thread yourself.

void main()
{
   Thread worker = new Thread(new ThreadStart(DoStuff));
   worker.Start();
}

private void DoStuff() 
{
  // long running work in here
}

You can also use the ParameterizedThreadStart if you want to throw in arguments to your DoStuff() method.

Ian
+1  A: 

Currently, you can use the ThreadPool to queue background tasks in programs that aren't Windows Forms Applications. In .NET 4.0, there are a lot of new features for parallel programming (like Parallel LINQ, ...). Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4 might be interesting for you.

Cheers Matthias

Mudu
+2  A: 

A very nice online resource for understanding threading in .NET with lots of samples; shared by Joseph Albahari.

KMan
I second this - Albahari's paper is an excellent place to start.
ebpower
A: 

As already mentioned use the BackgroundWorker and take a look at this answer and this answer.

Oliver
+1  A: 

Or if you use .net 4.0 you can use the task framework, it is nice. But be carefull not writting to the UI controls from another thread.

Pablo Castilla