C# 并发队列ConcurrentQueue

c# 同时被 2 个专栏收录
23 篇文章 0 订阅
12 篇文章 0 订阅

测试函数

static async Task RunProgram()
{
    var taskQueue = new ConcurrentQueue<CustomTask>();
    var cts = new CancellationTokenSource();
    //生成任务添加至并发队列
    var taskSource = Task.Run(() => TaskProducer(taskQueue));
    //同时启动四个任务处理队列中的任务
    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;
    //向任务发送取消信号
    cts.CancelAfter(TimeSpan.FromSeconds(2));
    await Task.WhenAll(processors);
}

产生任务
static async Task TaskProducer(ConcurrentQueue<CustomTask> 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);
    }
}

执行任务

static async Task TaskProcessor(ConcurrentQueue<CustomTask> 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; }
}

调用

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


  • 0
    点赞
  • 0
    评论
  • 8
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值