I need a method that returns a Task<string>
with empty string like
public static Task<string> AsyncTest()
{
return new Task<string>(() => string.Empty); //problem here
// this method would work:
// return new WebClient().DownloadStringTaskAsync(@"http://www.google.de");
}
public static void Workdl(string input)
{
Console.Write("OUT: " + input.Substring(0, 100));
}
This snippet compiles but when I call it like
Task<string> dlTask = AsyncTest();
Workdl(await dlTask);
await Task.WhenAll(dlTask); //Task never completes
it never determines.
The Task<TResult> return type is used for an async method that contains a return statement in which the operand is TResult . In the following example, the GetLeisureHoursAsync method contains a return statement that returns an integer.
The async method returning Task in C# It means the async method either does not have a return statement in it or it may contain a return statement that doesn't return any value. Such type of async methods returns void if they run synchronously.
You want to return a task result to the client. Set the task's Result property with your user defined result object. The task's Result property is serialized and returned back to the client.
A task is an object that represents some work that should be done. The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.
You can use Task.FromResult()
return Task.FromResult(string.Empty);
Unless you're writing your own task management system you should probably never use new Task(...)
.
However, that aside, the reason why this doesn't work in this case is because a new Task(...)
doesn't start by itself. It just constructs the task object around your delegate.
You should either explicitly start it:
var t = new Task(() => string.Empty);
t.Start();
return t;
Or simply use Task.Run
instead:
return Task.Run(() => string.Empty);
(this would be my recommendation to avoid using new Task(...)
)
Now, in this case I would go for something different altogether.
If you don't actually need to run the task, you can simply create an already completed task around an existing result. The reason I say "if" is that your example in the question may be dumbed down for the sake of this question and you may actually have code in there, in which case you should go for the code above this paragraph. However, if you need to adhere to an async method signature returning a task but doesn't actually need to spin up a task, then do this:
return Task.FromResult(string.Empty);
This simply "starts out already completed".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With