'How to execute tasks synchronously and in FIFO order in Windows Runtime?

I want to do the following:

  1. Execute some actions in order of scheduling function call.
  2. Execute them exclusively and wait for top-level actions to finish before starting next action.

I wrote the following code but I don't like it. Is there a better way? May be I should somehow implement TaskScheduler but I don't know how to await for top-level functions.

sealed class TaskSequence
{
    readonly object _critical = new object();
    Task _head;

    public Task<TResult> RunAsync<TResult>(Func<TResult> action)
    {
        lock (_critical)
        {
            var _previous = _head;
            var _next = Task.Run(() => TaskFunc(_previous, action));
            _head = _next;

            return _next;
        }
    }

    static async Task<TResult> TaskFunc<TResult>(Task _previous, Func<TResult> action)
    {
        if (_previous != null)
            await _previous;
        return action.Invoke();
    }
}


Solution 1:[1]

You can just use ConcurrentExclusiveSchedulerPair:

sealed class TaskSequence
{
  private readonly TaskFactory _factory = new TaskFactory(
      new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler);

  public Task<TResult> RunAsync<TResult>(Func<TResult> action)
  {
    return _factory.StartNew(action);
  }
}

Solution 2:[2]

This is old question, but still an answer can be usefull for someone.

Lock will not guarantee task ordering, You should use TaskScheduler.

You can use FifoTaskScheduler code from here: http://orderofcode.com/2016/05/06/fifo-order-task-scheduler/

or even more complicated one that allows to make different levels of concurency: https://msdn.microsoft.com/en-us/library/ee789351%28v=vs.100%29.aspx

or You can use TaskScheduler implementation from Microsoft samples. You can find it under ParallelExtensionsExtras/TaskSchedulers in https://code.msdn.microsoft.com/samples-for-parallel-b4b76364

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephen Cleary
Solution 2 bzyku