【发布时间】:2018-01-11 09:44:57
【问题描述】:
我正在尝试使用 .Net Core Framework 创建一个运行异步函数的 Web 服务。
此函数必须在其自己的线程中执行并返回一个新值,该值将发送给正确的调用者。 该服务必须在我的异步函数运行时侦听其他调用,并为每个调用启动一个新线程。 线程完成后,我希望将响应发送给原始调用者。 我试过这种方式:
在我的控制器中,我有:
[Route("api/orchestration")]
public class OrchController : Controller
{
[HttpGet("{value}")]
public void RunOrchestration(int value)
{
Program.GetResultAsync(value); // Notice that no value is returned but it respects the asynchronicity and the multithreading as asked
}
}
在我的主要课程中:
public async static Task<string> GetResultAsync(int i)
{
return await OrchestrationAsync(i);
}
public static Task<string> OrchestrationAsync(int i)
{
return Task.Run<string>(() => { return r = Orchestration(i); });
}
public static string Orchestration(Object i)
{
// This function is an orchestrator of microservices that talk asynchronously through a MOM
// Just consider that it returns the value I want in a string
return result;
}
如您所见,我希望我的函数 GetResultAsync 返回一个字符串,该字符串的值将发送给调用者。 然而我不能有这样的东西(见下面的代码),因为 GetResultAsync 返回一个任务而不是一个字符串:
public string RunOrchestration(int value)
{
return r = Program.GetResultAsync(value);
}
如果我在 RunOrchestration 中放置一个 await,它会等待响应并表现为一个同步函数。
任何人都知道如何获得我的回复并将其返回给适当的来电者?
提前致谢! :)
【问题讨论】:
-
阅读 SignalR
-
async != 并行执行
-
The service must be listening for other calls while my async function is running, and start a new thread for each call-> 你知道调用是默认并发处理的,除非你故意禁用它?那么为什么要进行这种建设呢? -
控制器动作在自己的线程中运行;该服务一次处理任意数量的请求;他们都返回到原来的调用者。这都是内置的。你要求什么行为?
-
如果我在控制器中直接调用 Orchestration(value),Web 应用程序将等待响应返回,然后再处理任何其他请求。我希望它仍在监听并为每个调用并行启动一个新线程。
标签: c# asp.net multithreading asp.net-core asp.net-core-webapi