0

If I have a portion of code which I would like be executed in a background thread, what is the easiest way in .NET (C#) for this to be achieved?

eg.

myObject1.myFunction(10, "Test");
myObject2.myFunction(20, "Test");
myObject3.myFunction(30, "Test");

What would be the easiest way to run the above code in a background thread?

CJ7
  • 22,579
  • 65
  • 193
  • 321

5 Answers5

2

If you're using 4.0+ .NET version, this would be shortest way I think:

Task.Factory.StartNew(() => 
{
   myObject1.myFunction(10, "Test");
   myObject2.myFunction(20, "Test");
   myObject3.myFunction(30, "Test"); 
})

More: http://msdn.microsoft.com/en-us/library/dd321439.aspx

Jeroen offered to use Thread.Start for this task, which is little bit shorter, but according to Skeet you loose these things, when you use plain Thread over Task:

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)
Community
  • 1
  • 1
Giedrius
  • 8,430
  • 6
  • 50
  • 91
1

Probably the easier way to do this is via a background worker:

class Program
{
  static BackgroundWorker _bw = new BackgroundWorker();

  static void Main()
  {
    _bw.DoWork += bw_DoWork;
    _bw.RunWorkerAsync ();
    Console.ReadLine();
  }

  static void bw_DoWork (object sender, DoWorkEventArgs e)
  {
    myObject1.myFunction(10, "Test");
    myObject2.myFunction(20, "Test");
    myObject3.myFunction(30, "Test");
  }
}
ColinE
  • 68,894
  • 15
  • 164
  • 232
1

I would use this:

new Thread( () =>
{
    myObject1.myFunction(10, "Test");
    myObject2.myFunction(20, "Test");
    myObject3.myFunction(30, "Test");
}).Start();

This will work in .NET version 4.5, 4, 3.5, 3.0, 2.0

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • How does `Task.Factory.StartNew` differ from `Thread.Start`? – CJ7 Oct 01 '13 at 07:36
  • The `Task.Factory.StartNew` is a new methology (introduced in .NET 4.5 (AsyncCTP library for 4.0)) used to build more responsive gui. Look here for more info: _Task Parallelism (Task Parallel Library)_ http://msdn.microsoft.com/en-us/library/dd537609.aspx The Task.Factory.StartNew will schedule an action on the threadpool. _unless other is specified (TaskCreationOptions)_ I only would use tasks in combination with UI (sequences of asynchronous instructions/IO file/network/database), because some code is triggered by the UI but i don't want it to block the UI thread while waiting for response. – Jeroen van Langen Oct 01 '13 at 07:55
  • For serverside/library I'd rather use async/threads. – Jeroen van Langen Oct 01 '13 at 07:55
1

As Giedrius said, if you are using .NET 4.0+ the TPL library is the way to go. A good practice is to check upon completion if the thread has failed due to an unhandled exception, using ContinueWith and task.IsFaulted.

Task.Factory.StartNew(() => 
{
    myObject1.myFunction(10, "Test");
    myObject2.myFunction(20, "Test");
    myObject3.myFunction(30, "Test"); 
}).ContinueWith(task => {
        if(task.IsFaulted)
        {
            AggregateException ex = task.Exception;
            //handle exception
        }
    });

0

Wrap using anonymous delegate:

ThreadPool.QueueUserWorkItem(delegate(object state) {

    // extract parameters from the object
    object[] array = state as object[];

    // your code here
    myObject1.myFunction(array[0], "Test");
    myObject2.myFunction(array[1], "Test");
    myObject3.myFunction(array[2], "Test");

}, 

// pass parameters as object
new object[] { 10, 20, 30 }

);

More Info: http://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.100).aspx

Abhitalks
  • 27,721
  • 5
  • 58
  • 81