简体   繁体   中英

Is it ok to await the same task from multiple threads - is await thread safe?

Is await thread safe? It seems the Task class is thread safe so I guess awaiting it is also thread safe but I haven't found a confirmation anywhere. Also is thread safety a requirement for custom awaiter - I mean for the IsCompleted, GetAwaiter, etc. methods? Ie if those methods are not thread safe, will await be thread safe? However, I don't expect needing a custom awaiter anytime soon.

An example of user scenario: Let's say I have a background task which returns a result asynchronously, which is then used from multiple threads:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace scratch1
{
    class Foo
    {
        Task<int> _task;

        public Foo()
        {
            _task = Task.Run(async () => { await Task.Delay(5000); return 5; });
        }

        // Called from multiple threads
        public async Task<int> Bar(int i)
        {
            return (await _task) + i;
        }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            Foo foo = new Foo();

            List<Task> tasks = new List<Task>();
            foreach (var i in Enumerable.Range(0, 100))
            {
                tasks.Add(Task.Run(async () => { Console.WriteLine(await foo.Bar(i)); })); 
            }

            Task.WaitAll(tasks.ToArray());
        }
    }
}

As you alluded to, await is thin enough that it doesn't see threads in the first place.

The code associated with await (the compiler-generated code within the state machine, and the support classes in the BCL) will only ever run on one thread at a time. (it can switch to a different thread when coming back from the awaitable, but the previous run will have already finished)

The actual thread-safety depends on the object you're awaiting.
It must have a thread-safe way to add callbacks (or await ing it twice at once may break).

In addition, it must call the callback exactly once, or it may break the state machine. (in particular, if it runs its callback on two threads at the same time, things will go horribly wrong)

Task is thread-safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM