Home > OS >  c# Task.Run Syntax
c# Task.Run Syntax

Time:07-08

I want to run listOrders() on a separate thread and make it awaitable. I have a method of this form, that compiles and works OK

private Task<ClearedOrdersReport> listOrdersAwaitable(int a, int b)
{
    Task<ClearedOrdersReport> t = Task.Run(() =>
       listOrders(a, b));
    return t;
}

I now want to add a second line to execute before the listOrders() call. I thought it would be trivial to change the single line lambda into a block style lambda, but I cannot figure out what the correct syntax is to get it to compile ? I am probably missing something obvious, but any help would be appreciated. Thanks

CodePudding user response:

You should use a statement lambda and return the result of listOrders.

 private Task<ClearedOrdersReport> listOrdersAwaitable(int a, int b)
 {
        Task<ClearedOrdersReport> t = Task.Run(() => {
           //add your second line here. 
           return listOrders(a, b);
        });
        return t;
 }

CodePudding user response:

There are some questions about what you are trying to do with the async/await elements, but one to call two many things where there was one is to use a helper method:

listOrders(a, b));

can become

DoWork(a,b);

and then

ClearedOrdersReport DoWork(int a, int b)
{
 ...
 return listOrders(a, b); 
} 
  • Related