授予关键财产

本文关键字:财产 | 更新日期: 2023-09-27 18:22:00

我有一个云应用程序,它使用优秀的WURFL库进行设备检测。

根据访问网站的设备类型,我们加载不同的资源。

直到最近,我一直在我的云应用程序中嵌入该服务。问题是,它为每个调试例程增加了3-5分钟,因为该服务支持检测成千上万的设备。.NET团队推荐的模式是将服务加载到Cache:中

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上,每次部署时人们都会起床吃零食等)

为了加快速度,我们最近创建了一个独立的云WEB API服务,该服务接收正确的信息并返回一个包含我们需要的所有信息的对象。我们从主动服务中获得了极好的响应时间(小于30ms)。

我现在面临的问题是,我不确定如何最好地改变我们的加载程序。

我可以让家庭控制器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,并通过在try-catch块内移动_device = await Device.GetDevice(Request.UserAgent);来处理异常


*它可以稍微增加每次操作的持续时间,但它允许同时进行更多的操作