我有一个使用优秀 WURFL 的云应用程序设备检测库。
根据访问网站的设备类型,我们加载不同的资源。
直到最近,我一直在将服务嵌入到我的云应用程序中。问题在于它会为每个调试例程增加 3-5 分钟,因为该服务支持检测数千台设备。 .NET 团队推荐的模式是将服务加载到缓存中:
var wurflDataFile = HttpContext.Current.Server.MapPath(WurflDataFilePath);
var configurer = new InMemoryConfigurer().MainFile(wurflDataFile);
var manager = WURFLManagerBuilder.Build(configurer);
HttpContext.Current.Cache["WurflManagerCacheKey"] = manager;
这 3-5 分钟的延迟让我们在一个由 5 名开发人员组成的团队中损失了大约 1-3 小时的生产时间(人们每次部署时都起床吃零食等,无论是在本地还是在 PPE 上)
为了加快速度,我们最近创建了一个独立的 Cloud WEB API 服务,它接收正确的信息并返回一个包含我们需要的所有信息的对象。我们从事件服务中获得了出色的(不到 30 毫秒)响应时间。
我现在面临的问题是,我不确定如何最好地更改我们的加载例程。
我可以让 HomeController async
并等待该属性,但这似乎很危险。处理此类问题的最佳方法是什么?
public static async Task<Device> GetDevice(RequestInfo requestInfo)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://mysiteurl.com");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("/api/devicedetection", requestInfo);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<Device>();
}
return new Device(Device.Default);
}
//Proposed Solution from team as it stands
public async Task<ActionResult> Index(string id)
{
_device = await Device.GetDevice(Request.UserAgent);
try
{
if (!string.IsNullOrEmpty(_userName))
{
Session.Add("CurrentDevice", _device);
ViewBag.DeviceType = _device.Type;
ViewBag.DeviceOs = _device.Os;
}
}
catch (Exception ex)
{
Response.Redirect("/Error");
}
return View();
}
最佳答案
在网站中使用 async-await
没有任何问题。如果您正在执行的操作自然是异步的(例如 I/O),则更可取。它减少了您的应用程序使用的资源并提高了可扩展性。*
我建议保持 async
命名标准并将 GetDevice
重命名为 GetDeviceAsync
并通过移动 _device = await 来处理异常Device.GetDevice(Request.UserAgent);
在 try-catch
block 中
* 它可以稍微增加每个操作的持续时间,但它允许同时进行更多操作
关于c# - 等待关键属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25855196/