- execute tasks
- post work items
- process asynchronous IO
- etc
using System;
using System.Threading;
namespace pc.threadpoolExample
{
class Program
{
static void Main(string[] args)
{
//create
background thread via threadpool
ThreadPool.QueueUserWorkItem(o => {
Thread.Sleep(500);//fires before main finishes
Console.WriteLine("Hello from the thread pool
1");
});
//create
background thread via threadpool
ThreadPool.QueueUserWorkItem(o=> {
Thread.Sleep(2000);// never fires, because main
finishes
Console.WriteLine("Hello from the thread pool
2");
});
var t = new Thread(() => {
Thread.Sleep(1000);
Console.WriteLine("hello from foregorund
thread");
});
//start
explicit thread
t.Start();
//join thread
back to main
t.Join();
Console.WriteLine("Main finished");
}
}
}
generally you wont create threads explicitly or via the threadpool class, odds are you'll leverage
- the Task Parallel library (TPL)
- the async/await keywords which abstract the TPL.
- the Asynchronous Pattern Model
- the Event based Asynchronous Pattern
- the Task based Asynchronous Pattern Model