简体   繁体   中英

Task.Run vs Invoke() difference

I need to pass an argument of type Task to some function that is not presented here. Inside the function this task will be executed in async way. If there a difference between these three ways to pass it:

1.

Task.Run((Func<Task>)(async () => Foo = await OperateAsync(id)))

2.

Task.Run(async () => Foo = await OperateAsync(id))

3.

((Func<Task>)(async () => Foo = await OperateAsync(id))).Invoke()

Yes.

1 and 2 differ in which overload of Task.Run gets called. The latter passes through the result.

1 and 2 force OperateAsync to the thread pool, 3 doesn't, which can be very visible depending on other details. For example, in desktop applications, if OperateAsync ends up accessing UI elements, it must not be called using Task.Run .

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