简体   繁体   中英

C# 7.0 standalone discard confusion | difference between _ = FooTask() and _ = Task.Run(FooTask)

I have a Task FooTask which should be called in background. A new feature in C# 7.0 is the discard function. As already asked ( C# 7.0 standalone discard confusion ) it is possible to call the Task in two ways. However, I have not yet been able to find out exactly how these two calls differ and whether they make a difference at all.

_ = Task.Run(FooTask);
_ = FooTask();

Discards make no difference here whatsoever; your code is identical to:

Task.Run(FooTask);
FooTask();

Even the generated IL is identical.

Discards simply make explicit that the returned Task is not required for any further process.

However, I have not yet been able to find out exactly how these two calls differ and whether they make a difference at all

The difference is the use of Task.Run which forces FooTask to run on a ThreadPool thread.

Without Task.Run , FooTask will run on the current thread until a continuation is scheduled, and the thread on which that continuation resumes is determined by the synchronisation context.

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