Home > Blockchain >  How can an "async" task return an integer and not a public one?
How can an "async" task return an integer and not a public one?

Time:11-24

I just had following piece of code, which did not compile:

public Task<int> Handle
{
    var result = <do_something_returning_an_int>();
    ...
    return result;
}

This gives compiler error `cannot implicitly convert type 'int' to 'System.Threading.Thread.Task'.

When I change this into:

async Task<int> Handle
{
    var result = <do_something_returning_an_int>();
    ...
    return result;
}

... no compiler error.

I know that async means that the task does not need to wait for the answer to arrive, but what does this have to do with typecasting?

CodePudding user response:

If you're not awaiting anything in your asynchronous method you omit the async keyword and return a Task instead of the result directly.

public Task<int> Handle
{
    var result = <do_something_returning_an_int>();
    ...
    return Task.FromResult(result);
}

As far as I can tell, doing that only makes sense if other code strictly expects a Task from your method.

This has of course nothing to do with access modifiers, you can combine async with public or any other access modifier.

I'd also recommend taking a look at the documentation

CodePudding user response:

try using task result and then iterate the results

Task<int> Handle
{
    return Task.Run(()=>
    {
       var result = <do_something_returning_an_int>();
       ...
       return result;
    }
}

List<Task<int>> tasks = new List<Task<int>>();
tasks.Add(Handle);
Task.WaitAll(tasks.ToArray());
for(int ctr = 0; ctr < tasks.Count; ctr  ) {
                if (tasks[ctr].Status == TaskStatus.Faulted)
                    output.WriteLine(" Task fault occurred");
                else
                {
                    output.WriteLine("test sent {0}",
                                      tasks[ctr].Result);
                    Assert.True(true);
                }
            }

or

Task<int> Handle
{
   return Task.FromResult(do_something_returning_an_int);
}
  • Related