Concurrency and Source Panels
Thread Local Context
Give each thread its own context value before storing a shared summary.
Thread Local Context
ThreadLocalContext.cs
using System;
using System.Threading;
class Program
{
static readonly ThreadLocal<int> WorkerScore = new ThreadLocal<int>(() => 0);
static int boost;
static int alphaResult;
static int betaResult;
static void AlphaWorker()
{
WorkerScore.Value = boost + 10;
alphaResult = WorkerScore.Value;
}
static void BetaWorker()
{
WorkerScore.Value = boost + 20;
betaResult = WorkerScore.Value;
}
static void Main()
{
int extra = ;
boost = extra;
Thread alpha = new Thread(AlphaWorker);
Thread beta = new Thread(BetaWorker);
alpha.Start();
beta.Start();
alpha.Join();
beta.Join();
int total = alphaResult + betaResult;
Console.WriteLine($"extra={extra}");
Console.WriteLine($"total={total}");
}
}
using System;
using System.Threading;
class Program
{
static readonly ThreadLocal<int> WorkerScore = new ThreadLocal<int>(() => 0);
static int boost;
static int alphaResult;
static int betaResult;
static void AlphaWorker()
{
WorkerScore.Value = boost + 10;
alphaResult = WorkerScore.Value;
}
static void BetaWorker()
{
WorkerScore.Value = boost + 20;
betaResult = WorkerScore.Value;
}
static void Main()
{
int extra = ;
boost = extra;
Thread alpha = new Thread(AlphaWorker);
Thread beta = new Thread(BetaWorker);
alpha.Start();
beta.Start();
alpha.Join();
beta.Join();
int total = alphaResult + betaResult;
Console.WriteLine($"extra={extra}");
Console.WriteLine($"total={total}");
}
}
using System;
using System.Threading;
class Program
{
static readonly ThreadLocal<int> WorkerScore = new ThreadLocal<int>(() => 0);
static int boost;
static int alphaResult;
static int betaResult;
static void AlphaWorker()
{
WorkerScore.Value = boost + 10;
alphaResult = WorkerScore.Value;
}
static void BetaWorker()
{
WorkerScore.Value = boost + 20;
betaResult = WorkerScore.Value;
}
static void Main()
{
int extra = ;
boost = extra;
Thread alpha = new Thread(AlphaWorker);
Thread beta = new Thread(BetaWorker);
alpha.Start();
beta.Start();
alpha.Join();
beta.Join();
int total = alphaResult + betaResult;
Console.WriteLine($"extra={extra}");
Console.WriteLine($"total={total}");
}
}
thread local
`ThreadLocal<T>` stores a separate value for each thread while the main thread reads ordinary shared results after `Join`.