Creating a run queue using Task.ContinueWith?

I have several actions that I want to perform in the background, but they must be performed synchronously one after another.

I was wondering if you should use the Task.ContinueWith method for this. Do you foresee any problems with this?

My code looks something like this:

private object syncRoot =new object();
private Task latestTask;

public void EnqueueAction(System.Action action)
{
    lock (syncRoot)
    {
        if (latestTask == null)
            latestTask = Task.Factory.StartNew(action);
        else
            latestTask = latestTask.ContinueWith(tsk => action());
    }
}
+5
source share
3 answers

This should work as designed (using the fact that the TPL will schedule a continuation immediately if the corresponding task has already been completed).

, (ConcurrentQueue) - , , , ..

+5

, , .

-, , . , . 85 000 , ( ). LOH, .

, , no-op . .

+7

I used this snippet and seems to have earned it as designed. The number of copies in my case does not work in thousands, but in one digit. However, no problem so far.

I would be interested in the ConcurrentQueue example, if any?

thank

0
source

All Articles