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



我有一个C# REST Service应用程序,它处理一堆传入的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 匹配服务。对于匹配服务,假设许多玩家可以使用">FindMatchAsIndividual"方法发出POST请求。

对于每次调用,我都会将玩家名称添加到列表中。当列表中有 2 个玩家名称时,创建对">FindMatchAsIndividual"的回调,此时可以将匹配的 json 表示形式发送回给进行 REST API 调用的人。

要实现这样的东西,显然它必须是异步的。每次调用">FindMatchAsIndividual"只会在列表中添加 1 个玩家姓名,我们无法创建只有 1 个玩家的匹配项。我们需要等待另一个玩家调用">FindMatchAsIndividual",然后才能创建 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();
}
}

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

最新更新