如何在 C# 中异步、并行地调用两个函数?
How do I call two functions asynchronously, in parallel, in C#?
我有两个相互独立的静态函数,单独使用时会消耗大量资源。
public static class Helper(){
public static void A(string username, int power, Model model)
{ /* do A things to the model */ }
public static void B(string username, Model model)
{ /* do B things to the model */ }
}
现在,他们被称为
public ActionResult Home(){
Model model = new Model();
A("Jared", 9001, model);
B("Jared", model);
return View("Home", model);
}
在我的控制器中(注意:不是真正的代码)。
我希望它们异步并排工作,然后当它们都完成后我想return进行同步处理,以便return具有更新的视图型号。
有没有办法做到这一点?我以前从未使用过异步 C# 或线程 C#,因此我很难解读我发现的示例。
TIA
我会像这里描述的那样使用任务并行库 https://msdn.microsoft.com/en-us/library/dd537609%28v=vs.110%29.aspx
我假设你的意思是异步并行。
首先更新您的函数以匹配如下内容:
public static async Task A(Model model) { /* ... */ }
public static async Task B(Model model) { /* ... */ }
然后将您的调用代码更新为如下所示:
public async Task<ActionResult> Home() {
var taskA = A(model);
var taskB = B(model);
await Task.WhenAll(taskA, taskB);
return View("Home", model);
}
这应该可以解决问题..
public async Task<ActionResult> Home()
{
var model = new Model();
var t1 = Helper.A("Jared", 9001, model);
var t2 = Helper.B("Jared", model);
await Task.WhenAll(new [] { t1, t2 });
return View("Home", model);
}
public static class Helper
{
public static async Task A(string username, int power, Model model)
{
/* do A things to the model */
}
public static async Task B(string username, Model model)
{
/* do B things to the model */
}
}
虽然这有很大的 "gotcha"。该模型必须能够处理 A()
和 B()
并行工作。
我有两个相互独立的静态函数,单独使用时会消耗大量资源。
public static class Helper(){
public static void A(string username, int power, Model model)
{ /* do A things to the model */ }
public static void B(string username, Model model)
{ /* do B things to the model */ }
}
现在,他们被称为
public ActionResult Home(){
Model model = new Model();
A("Jared", 9001, model);
B("Jared", model);
return View("Home", model);
}
在我的控制器中(注意:不是真正的代码)。
我希望它们异步并排工作,然后当它们都完成后我想return进行同步处理,以便return具有更新的视图型号。
有没有办法做到这一点?我以前从未使用过异步 C# 或线程 C#,因此我很难解读我发现的示例。
TIA
我会像这里描述的那样使用任务并行库 https://msdn.microsoft.com/en-us/library/dd537609%28v=vs.110%29.aspx
我假设你的意思是异步并行。
首先更新您的函数以匹配如下内容:
public static async Task A(Model model) { /* ... */ }
public static async Task B(Model model) { /* ... */ }
然后将您的调用代码更新为如下所示:
public async Task<ActionResult> Home() {
var taskA = A(model);
var taskB = B(model);
await Task.WhenAll(taskA, taskB);
return View("Home", model);
}
这应该可以解决问题..
public async Task<ActionResult> Home()
{
var model = new Model();
var t1 = Helper.A("Jared", 9001, model);
var t2 = Helper.B("Jared", model);
await Task.WhenAll(new [] { t1, t2 });
return View("Home", model);
}
public static class Helper
{
public static async Task A(string username, int power, Model model)
{
/* do A things to the model */
}
public static async Task B(string username, Model model)
{
/* do B things to the model */
}
}
虽然这有很大的 "gotcha"。该模型必须能够处理 A()
和 B()
并行工作。