How can I assign a name to a task in TPL

后端 未结 11 1277
礼貌的吻别
礼貌的吻别 2021-02-12 10:24

I\'m going to use lots of tasks running on my application. Each bunch of tasks is running for some reason. I would like to name these tasks so when I watch the Parallel Tasks wi

11条回答
  •  深忆病人
    2021-02-12 11:29

    public class NamesTask {
        readonly Queue _taskqueue = new Queue();
        private readonly object _queueLock = new object();
    
        public Task RunTask(Action action) {
            //incoming task must be queued as soon as it arrives
            var inComingTask = new Task(action);
    
            lock (_queueLock) {
                _taskqueue.Enqueue(inComingTask);
            }
    
            return Task.Factory.StartNew(() => {
                //run all actions one by one..
                while (true) {
                    lock (_queueLock) { //only one task must be performed at a 
                        if (_taskqueue.Count == 0) return;
    
                        var outTask = _taskqueue.Dequeue();
    
                        outTask.Start();
                        outTask.Wait();
    
                        Console.WriteLine("done....");
                    }
                }
            });
        }
    }
    

提交回复
热议问题