Skip to content

Instantly share code, notes, and snippets.

@kasajian
Created October 30, 2024 02:02
Show Gist options
  • Save kasajian/944916bf1dabd3cb667c76cf722eeef6 to your computer and use it in GitHub Desktop.
Save kasajian/944916bf1dabd3cb667c76cf722eeef6 to your computer and use it in GitHub Desktop.
Sample using ConcurrentExclusiveSchedulerPair
// Reference: https://stackoverflow.com/a/12069460/75129
using static System.FormattableString;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConcurrentExclusiveSchedulerPair_SampleA
{
class SampleWorker
{
private static readonly object v = new object();
private readonly string identity;
private object sync = v;
private int id;
public SampleWorker(string identity)
{
Console.WriteLine(Invariant($"Using: {identity}"));
this.identity = identity;
}
public void Do()
{
int myId = Interlocked.Increment(ref id);
Log(Invariant($"{identity}: [{myId}] start"));
Task.Delay(1000).Wait();
Log(Invariant($"{identity}: [{myId}] end"));
void Log(string msg)
{
lock (sync)
{
Console.WriteLine(msg);
}
}
}
}
internal class Program
{
static void Main(string[] args)
{
UsingRegularScheduler();
UsingConcurrentExclusiveScheduler();
}
private static void UsingConcurrentExclusiveScheduler()
{
var schedulerPair = new ConcurrentExclusiveSchedulerPair();
var exclusiveTaskFactory = new TaskFactory(schedulerPair.ExclusiveScheduler);
//var x = schedulerPair.Completion;
var work = new SampleWorker("ConcurrentExclusiveScheduler");
Task.WaitAll(Enumerable.Range(0, 10)
.Select(i => exclusiveTaskFactory.StartNew(work.Do)).ToArray());
}
private static void UsingRegularScheduler()
{
var work = new SampleWorker("RegularScheduler");
Task.WaitAll(Enumerable.Range(0, 10)
.Select(i => Task.Run(work.Do)).ToArray());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment