Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation on Tasks

Tags:

c#

task

I'd like some clarification on code I didn't do and have to modify in a service.

Here's some parts of the code of the service

private Thread _thread;
private ConcurrentQueue<Task> _tasks = new ConcurrentQueue<Task>();
private Task _runningTask = null;

protected override void OnStart(string[] args)
{
    _thread = new Thread(WorkerThreadFunc);
    _thread.IsBackground = true;
    _thread.Start();
}

private void WorkerThreadFunc()
{
    InitDb();

    while (!_shutdownEvent.WaitOne(1000))
    {
        if (_runningTask == null || _runningTask.IsCompleted)
        {
            Task task;
            if (_tasks.TryDequeue(out task))
            {
                _runningTask = task;
                _runningTask.Start();
            }
        }
    }
}


private void RunReport(int reportID)
{
    var task = new Task(id =>
    {
        //Task code
    }, reportID);

    _tasks.Enqueue(task);
}

And so, this all works well

The thing is, I want to add other tasks to the task queue, but I don't have any ID to give them (the task in the code runs a report and uses the reportID, but the other tasks aren't linked to one report in particular).

Is there a way to create a Task without giving it an ID (which I doubt), or is there something i'm completely missing ?

like image 690
Shadowxvii Avatar asked Apr 30 '26 02:04

Shadowxvii


1 Answers

Is there a way to create a Task without giving it an ID (which I doubt), or is there something i'm completely missing ?

Yes, just use:

_tasks.Enqueue(new Task(() => {
       // Your code here
   });

That being said, this is not an idiomatic usage of the Task class. In general, the Task and Task<T> classes are meant to always be running - not created and started later.

like image 129
Reed Copsey Avatar answered May 01 '26 17:05

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!