c# - Is it possible to determine if a method returns a Task and await it if it does? -


my goal pass function return type execute method , serialize , store results. below rough idea of trying do, won't compile gets idea across. suppose should able handle nested tasks recursively. thoughts?

public static tresult execute<tresult>(func<tresult> method)         tresult : class     {          var result = method();         if(result task)         {             var taskresult = await result;             storeresult(taskresult);         }         else         {             storeresult(result);         }     } 

i agree lee's comment having separate overload func<task<tresult>> right solution.

but if want using 1 overload, use reflection , dynamic make work:

public async static task execute<tresult>(func<tresult> method) tresult : class {     var result = method();      if (typeof(tresult).isgenerictype         && typeof(tresult).getgenerictypedefinition() == typeof(task<>))     {         var taskresult = await (dynamic)result;         storeresult(taskresult);     }     else     {         storeresult(result);     } } 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -