如何在REST请求上实现异步回调

时间:2018-04-13 02:43:18

标签: c# multithreading rest

我有一个C#REST服务应用程序,它处理一堆传入的HTTP请求,其中一些是POST,其中一些是GET。它们通常是标准的。我实现了一堆包含路由的Web API控制器来处理这些HTTP请求。

public class MatchController : ApiController
{
    [Route("FindMatchAsIndividual")]
    [HttpPost]
    public async Task<HttpResponseMessage> FindMatchAsIndividual(string playername)
    {
         //Add player name to matchmaking list
         //if there is a match, return json string representation of a match
    }

}

但我的用例是实现1v1配对服务。对于配对服务,假设许多玩家可以使用&#34; FindMatchAsIndividual &#34;方法。

对于每次通话,我都会将玩家名称添加到列表中。当列表中有2个玩家名称时,创建一个回调到&#34; FindMatchAsIndividual &#34;,此时可以将匹配的json表示发送回创建REST API的任何人调用

要实现这样的东西,显然它必须是异步的。每次拨打&#34; FindMatchAsIndividual &#34;只会在列表中添加1个玩家名称,而我们无法与1个玩家创建匹配。我们需要等待其他玩家打电话给&#34; FindMatchAsIndividual &#34;在我们创建1v1匹配并返回结果之前。

这样做的最佳方式是什么?一种方法是启动后台线程/任务,使用EventHandlers对 FindMatchAsIndividual 方法进行回调。我不知道在哪里创建线程。我想我可能会把它 WebAPIConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}",
            defaults: new { id = RouteParameter.Optional }
        );

        Thread thread = new Thread(RunMatchMakingService);
        thread.Start();
    }
}

1 个答案:

答案 0 :(得分:0)

当玩家调用api时,将玩家添加到列表中,当玩家数量超过1(可能有很多玩家)时,在缓存列表中标记前2个玩家,然后按名称将结果返回给玩家,并从缓存列表中删除这两个播放器。