C ා concurrent queue

Time:2020-10-29

Test function

static async Task RunProgram()
{
var taskQueue = new ConcurrentQueue();
var cts = new CancellationTokenSource();
//Build task added to concurrent queue
var taskSource = Task.Run(() => TaskProducer(taskQueue));
//Start four tasks simultaneously to process the tasks in the queue
Task[] processors = new Task[4];
for(int i =1;i <= 4; i++)
{
string processId = i.ToString();
processors[i – 1] = Task.Run(
() => TaskProcessor(taskQueue, “Processor ” + processId, cts.Token)
);
}
await taskSource;
//Send cancel signal to task
cts.CancelAfter(TimeSpan.FromSeconds(2));
await Task.WhenAll(processors);
}

Generating tasks
static async Task TaskProducer(ConcurrentQueue queue)
{
for(int i= 0;i < 20; i++)
{
await Task.Delay(50);
var workItem = new CustomTask { Id = i };
queue.Enqueue(workItem);
Console.WriteLine(“task {0} has been posted”, workItem.Id);
}
}
Carry out the task

static async Task TaskProcessor(ConcurrentQueue queue, string name, CancellationToken token)
{
CustomTask workItem;
bool dequeueSuccesful = false;
await GetRandomDelay();
do
{
dequeueSuccesful = queue.TryDequeue(out workItem);
if (dequeueSuccesful)
{
Console.WriteLine(“task {0} has been processed by {1}”, workItem.Id, name);
}
await GetRandomDelay();
}
while (!token.IsCancellationRequested);
}

static Task GetRandomDelay()
{
int delay = new Random(DateTime.Now.Millisecond).Next(1500);
return Task.Delay(delay);
}

class CustomTask
{
public int Id { get; set; }
}

call
static void Main(string[] args)
{
Task t = RunProgram();
t.Wait();
Console.ReadKey();
}

 

Reprint https://blog.csdn.net/conquerwave/article/details/50830648

Recommended Today

Integrated Next.js Efficient front end architecture of DVA and DVA [email protected]/joy

@symph/joy introduce https://lnlfps.github.io/symph-joy @The goal of Symphony / joy is to create pleasant front-end applications next.js With the ability of server-side rendering and zero configuration, it can develop front-end business as easily as DVA. The project has been used in the production environment. If you have any questions, help, bug feedback, feature discussion, please contact […]