Skip to content

Instantly share code, notes, and snippets.

@harshityadav95
Created July 8, 2017 20:36
Show Gist options
  • Save harshityadav95/96567de0a37849ffea349c980858daa4 to your computer and use it in GitHub Desktop.
Save harshityadav95/96567de0a37849ffea349c980858daa4 to your computer and use it in GitHub Desktop.
Thread Pool in c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace After017
{
class Program
{
static void Main(string[] args)
{
int ports; int max;
ThreadPool.GetMaxThreads(out max, out ports);
Console.WriteLine("Max:" + max.ToString());
ThreadPool.SetMaxThreads(100, 1);
// one
ThreadPool.QueueUserWorkItem(CallBack, "One");
// two
ThreadPool.QueueUserWorkItem(CallBack, "One");
ThreadPool.QueueUserWorkItem(CallBack, "Two");
Console.ReadLine();
// overload!
var callbacks = Enumerable.Range(1, 10).Select(x => new Action(() => { ThreadPool.QueueUserWorkItem(CallBack, x); }));
Parallel.Invoke(callbacks.ToArray());
Console.Read();
}
private static void CallBack(object state)
{
Thread.Sleep(new Random().Next(3, 100));
Console.WriteLine("{0}\r\n", state);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment