| C# Threading QA-1-10 | C# Threading QA-21-30 | |
Dot net Framework (C#) Threading Question Answers - 11-20 |
Synchronization primitives can be roughly divided into three categories:
Interlocked class (e.g., Add, Increment, Exchange, CompareExchange).// Enter the thread pool via asynchronous delegates
static void Main()
{
Func<string, int> method = DoWork;
IAsyncResult cookie = method.BeginInvoke("From Asynchronous delegates", null, null);
// ...Do other work here in parallel
int result = method.EndInvoke(cookie);
Console.WriteLine("String length: " + result);
}
static int DoWork(string s)
{
return s.Length;
}
// Output
// String length: 27
using System.ComponentModel;
using System.Threading;
class BackgroundWorkerEx
{
static BackgroundWorker _bw = new BackgroundWorker();
static void Main()
{
int worker = 0, io = 0;
ThreadPool.GetAvailableThreads(out worker, out io);
Console.WriteLine("Total Threads in the Pool: -> " + worker + ", IO thread-> " + io);
_bw.DoWork += bw_DoWork;
_bw.RunWorkerAsync("Message to worker");
Console.ReadLine();
}
static void bw_DoWork(object sender, DoWorkEventArgs e)
{
int worker = 0, io = 0;
ThreadPool.GetAvailableThreads(out worker, out io);
Console.WriteLine("Remaining Threads: -> " + worker + ", IO thread-> " + io);
Console.WriteLine(e.Argument); // "Message to worker"
}
}
// Output
// Total Threads in the Pool: -> 3200, IO thread-> 3200
// Remaining Threads: -> 3198, IO thread-> 3200
// Message to worker
using System.Threading;
using System.Threading.Tasks;
class ProgramThreadPool
{
static void Main()
{
int worker = 0, io = 0;
ThreadPool.GetAvailableThreads(out worker, out io);
Console.WriteLine("Total Threads in the Pool: -> " + worker + ", IO thread-> " + io);
Task.Factory.StartNew(DoWork);
}
static void DoWork()
{
int worker = 0, io = 0;
ThreadPool.GetAvailableThreads(out worker, out io);
Console.WriteLine("Remaining Threads: -> " + worker + ", IO thread-> " + io);
Console.WriteLine("Hello from the thread pool!");
}
}
// Output
// Total Threads in the Pool: -> 3200, IO thread-> 3200
// Remaining Threads: -> 3199, IO thread-> 3200
// Hello from the thread pool!
Interlocked The System.Threading.Interlocked class provides atomic operations that can be used to perform operations like incrementing, decrementing, or exchanging values without the risk of race conditions.Use Thread.CurrentThread property.
To pass arguments to a thread’s target method is to execute a lambda expression that calls the method with the desired arguments:
static void Main()
{
Thread t = new Thread(() => Print("Hello from t!"));
t.Start();
}
static void Print(string message)
{
Console.WriteLine(message);
}
No, a blocked thread does not consume CPU resources.
| C# Threading QA-1-10 | C# Threading QA-21-30 | |