Skip to main content
 首页 » 编程设计

c#之WebApi如何写并行函数

2024年02月25日29sxdcgaq8080

我是 webapi 的新手,请帮助我如何编写并行方法。

 public IHttpActionResult GetData() 
            {   
    Parallel.Invoke(() => ObjRepo.GetEmployee());     
//Here how can i pass its to ok return type    
                return Ok(); 
            } 

请您参考如下方法:

您可以使用 Task.WhenAll 并行执行多个方法。

You apply the Task.WhenAll method to a collection of tasks. The application of WhenAll returns a single task that isn’t complete until every task in the collection is completed. The tasks appear to run in parallel, but no additional threads are created. The tasks can complete in any order.

以下是示例代码

   var method1Task = Method1Async(); 
   var method2Task = Method2Async(); 
   await Task.WhenAll(method1Task, method1Task); 

你的方法应该是这样的

  public async Task Method1Async() 
        { 
          //Implementation  
        } 
  public async Task Method2Async() 
        { 
         //Implemenation 
        } 

更多详情可以查看here