1

Please consider the code :

public class TestResource<T>
{
        public Task<T> Get()
        {
            String measures = null;
            // Some heavy action that put data in "measures"

            // now return Task<T> with "measures" for T="Measure" ...
            return measures as Task<T>;  // alwsys returns null ...
        }
}

With its MAIN:

   TestResource<Measure> testMeasure = new TestResource<Measure>();
   Task<Measure> taskMeasure = testMeasure.Get();
   Measure result = taskMeasure.Result;    // !! This one is ALWAYS NULL
   if (result != null)
   {
     // Show result to the user
   }

taskMeasure is always NULL.

How can we return the Task<T> (with the correct value for the requested T) from the GET method properly ?

Filburt
  • 17,626
  • 12
  • 64
  • 115
JAN
  • 21,236
  • 66
  • 181
  • 318
  • 1
    String is not a task. So your `measures as Task` [returns `null`](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-conversion-operators#as-operator). Apparently you wanted [`Task.FromResult`](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.fromresult?view=netframework-4.8). Judging by the `as` and the following [`.Result`](https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html), you might want to [refresh](https://blog.stephencleary.com/2012/02/async-and-await.html) your understanding of how async/await works. – GSerg Jul 20 '19 at 15:15
  • @KirkLarkin: Impossible , `Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'System.Threading.Tasks.Task` – JAN Jul 20 '19 at 15:18
  • 1
    That has nothing to do with tasks, rather it is [improper use of generics](https://stackoverflow.com/a/8171547/11683). If you are returning a string, declare the method as `Task` as opposed to `Task`. – GSerg Jul 20 '19 at 15:20
  • @GSerg: I need it as a general function , to return something for any type , no necessarily `String` – JAN Jul 20 '19 at 15:23
  • I would perform the heavy work as part of the task. Creating a task once the work is done is pretty useless. `return Task.Run(() => { string measures = null; heavy work here; return measures; });` – Olivier Jacot-Descombes Jul 20 '19 at 15:23
  • @JAN I wonder how you do that given the `String measures = null;`. Does your code look similar to https://stackoverflow.com/q/8171412/11683 at all? – GSerg Jul 20 '19 at 15:25
  • @GSerg Do you think we should reopen this or maybe add what you linked as an additional dupe? I'm happy to just reopen and let someone else take care of it. – Kirk Larkin Jul 20 '19 at 15:26
  • 1
    @KirkLarkin The duplicate is perfect. It's just that it's not very useful for the OP because they are messing with generics in the wrong way. They should stop that, and then the duplicate fully applies. – GSerg Jul 20 '19 at 15:34

0 Answers0