Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Task' does not contain a definition for 'CompletedTask' for C#

Tags:

c#

task

I'm following the tutorial at https://discord.foxbot.me/docs/guides/getting_started/intro.html to a tee, and yet I'm getting an error when I try to use

return Task.CompletedTask

and I get this error

'Task' does not contain a definition for 'CompletedTask'

I am

using System.Threading.Tasks
like image 632
Thomas Wood Avatar asked Jul 06 '17 02:07

Thomas Wood


People also ask

What is task CompletedTask in C#?

Task. CompletedTask property is important when you need to give a caller a dummy Task (that doesn't return a value/result) that's already completed. This might be necessary to fulfill an "interface" contract or testing purposes. Task. FromResult(data) also returns a dummy Task, but this time with data or a result.

How do I return a null task?

Returning null from a non-async Task-returning method One way to prevent this NRE while still returning null is to check that the result of the method is not null and await a valid Task if it is. We can do this with the null-coalescing operator; for example: result = await (NonAsyncFoo() ?? Task.

What happens if you await a completed task?

You can think of it as being lazy, if you await a task that is already completed it returns immediately. You could await it several times on different threads and it would only return once it has the result (or is faulted). Task.


2 Answers

If you are unable to upgrade the .NET Framework version, simply

replace Task.CompletedTask with Task.FromResult(0).

like image 181
JDawg Avatar answered Sep 28 '22 04:09

JDawg


Task.CompletedTask is a static property added in .NET 4.6. Here is its source, and here is its MSDN page which shows the minimum framework version.

Just for completeness, here is how you change the .NET Framework version you are using in your project.

Project Properties, Target Framework

like image 26
Scott Avatar answered Sep 28 '22 03:09

Scott