Skip to main content
 首页 » 编程设计

c#之我应该在这里使用什么线程异步

2024年02月13日11del

我不确定在这种情况下该使用什么。

我有一个基本上可以做到这一点的 asp.net web api 方法

  1. 从用户附近的 foursquare 中找到兴趣点。
  2. 使用 foursquare 位置在我的数据库中进行查询,以查找有关用户附近兴趣点的独特数据。

但是,由于我需要存储一些 foursquare 信息以链接到该位置的我的唯一数据,我决定将所有信息存储在我的数据库中,并将我的数据库用作我的缓存系统。

这意味着我必须将任何新的兴趣点插入到我的数据库中,检查它是否存在,如果存在则跳过它,或者如果存在则检查上次刷新日期(foursquare 政策规定所有数据必须在之后刷新30 天),如果超过了刷新日期,我必须更新数据。

我想减慢用户的速度,必须等待上述情况发生。我希望我的代码执行第 1 步,然后执行我刚才提到的操作,同时执行第 2 步。

一旦第 2 步完成,我想返回数据并让用户继续前进。如果我的缓存系统没有完成,那么它应该继续运行但不会让用户陷入困境。

我不会在第 2 步中使用这些新结果中的任何一个,就好像我正在插入它一样,此时我不会在该位置有任何数据。

不确定我是否需要创建线程或使用 async/await 来实现此目的。

编辑

这是我想做的

public HttpResponseMessage Get() 
{ 
    // this will do a foursquare lookup to find all stores near the user 
    // I want to insert them into my database and link it to my unquie data.  
    // stores pulled from foursquare will 
    // a) Be new and not in my database 
    // b) exist in my database but have been refreshed lately 
    // c) have not been refreshed in timeframe of foursquare policy 
    // THIS SHOULD WORK IN THE BACKGROUND 
    storeService.PointsOfInterestNearUser(80, -130); //As you can see it is  
                        //void. Not sure where to put the async/await stuff 
 
    // find this product. Should be happening at the same time as above line. 
    var product = productService.FindProduct("Noodles"); 
 
    //This will get returned to the user.  
    // the new stores taht are being added in StoreNearUser  
    //won't effect this search as I will have not data on this new store 
    // if existing store is being refreshed it is possible old  
    //address might be picked up... 
    //I can live with that as I doubt the address will change much. 
 
    // this should happen after product 
    var allStores = storeService.FindStoresThatHaveItem(product); 
 
    // this should be returned as soon as above line is finished.  
    //If StoreNearUser is not done, it should keep going but not hold up user. 
    return allStores; 
} 
public void StoresNearUser(double latitude, double longitude) 
{ 
    // get all categories I can about in foursquare.  
    //First time from db otherwise cached. 
    List<StoreCategory> storeCategories = GetStoreCategories(); 
 
    // do a request and get everything in near the user 
    //(provided it is also in a category I care about) 
    var request = CreateFoursquareStoreRequest 
                       (latitude, longitude, storeCategories); 
 
    // do the actual call. 
    var response = client.Execute<VenueSearch>(request); 
 
 
    if (response.StatusCode == System.Net.HttpStatusCode.OK) 
    { 
// start going through the results, add or update or skip of entry will happen 
        AddUpdateStores(storeCategories, response); 
    } 
    else 
    { 
        ErrorSignal.FromCurrentContext().Raise(response.ErrorException); 
    } 
} 

编辑 2

public async Task StoresNearUser(double latitude, double longitude) 
{ 
// get all categories I can about in foursquare. First time from db otherwise cached. 
    List<StoreCategory> storeCategories = GetStoreCategories(); 
 
// do a request and get everything in near the user(provided it is also in a category I care about) 
    var request = CreateFoursquareStoreRequest(latitude, longitude, storeCategories); 
 
    await client.ExecuteAsync<VenueSearch> 
              (  request 
                 , response => 
                     { 
                         if (response.StatusCode == System.Net.HttpStatusCode.OK) 
                         { 
                             AddUpdateStores(storeCategories, response); 
                         } 
                         else 
                         { 
                             ErrorSignal.FromCurrentContext() 
                                        .Raise(response.ErrorException); 
                         } 
                     } 
              ); 
} 

给我这个错误

Cannot await 'RestSharp.RestRequestAsyncHandle' 

我也不明白 Task 和 void 之间的区别。根据我的阅读,如果你只使用 Task 这意味着你没有发送任何有意义的东西,那么为什么不使用 void 呢?

编辑 2 我找到了 this post向我展示如何为 Restsharp 制作包装器。这不是我想要的 100%,但这是一个单独的问题。

public async Task StoresNearUser(double latitude, double longitude) 
{ 
    List<StoreCategory> storeCategories = GetStoreCategories(); 
 
    var request = CreateFoursquareStoreRequest 
                    (latitude, longitude, maxRadius, returnLimit, storeCategories); 
 
    var response =  await client.GetResponseAsync(request); 
 
    if (response.StatusCode == HttpStatusCode.OK) 
    { 
// had to use json.net right now as the wrapper does not expose restsharps deserilizer 
        var venue = JsonConvert 
                    .DeserializeObject<VenueSearch>(response.Content); 
        AddUpdateStores(storeCategories, venue); 
    } 
    else 
    { 
        ErrorSignal.FromCurrentContext() 
                   .Raise(response.ErrorException); 
    } 
} 
 
public async Task<HttpResponseMessage>Get() 
{ 
    await storeService.PointsOfInterestNearUser(80, -130); 
    var product = productService.FindProduct("Noodles"); 
    var allStores = storeService.FindStoresThatHaveItem(product); 
    return allStores; 
 } 

当我从调试器中观察时,它看起来仍然一切正常。我认为 product 和 allStores 需要,因为我需要产品才能找到商店,但 PointsOfInterestNearUser 应该与查找产品。

编辑 3 这是我的 FindProduct 方法。不确定对我来说异步是什么,看起来一切都需要等待。

public ResponseResult<Product> FindProduct(string barcode) 
    { 
        ResponseResult<Product> responseResult = new ResponseResult<Product>(); 
        Product product = null; 
 
        try 
        { 
 
            var findBarCode = context.Barcodes.Where(x => x.Code == barcode).Select(x => x.Product).FirstOrDefault(); 
 
            responseResult.Response = product; 
 
            if (product == null) 
            { 
                responseResult.Status.Code = HttpStatusCode.NotFound; 
            } 
            else 
            { 
                responseResult.Status.Code = HttpStatusCode.OK; 
            } 
        } 
        catch (SqlException ex) 
        { 
            ErrorSignal.FromCurrentContext().Raise(ex); 
            responseResult.Status.Code = HttpStatusCode.InternalServerError; 
            responseResult.Status.Message = GenericErrors.InternalError; 
        } 
 
        return responseResult; 
    } 

编辑4

仍然不确定如何执行 Task.WhenAll()

 public async Task<HttpResponseMessage>Get() 
    { 
      Task[] tasks = new Task[2]; 
      tasks[0] = storeService.PointsOfInterestNearUser(80, -130); 
      tasks[1] = productService.FindProduct("Noodles"); 
 
       await Task.WhenAll(tasks); 
 
       // not sure how to get product back out. I looked in the debugger and saw a "Result" that has it but when I do tasks[1].Result inetllisene cannot find .Result 
       var allStores = storeService.FindStoresThatHaveItem(product); 
       return allStores; 
     } 

请您参考如下方法:

我建议为此使用async/await。更新缓存是可以接受从 ASP.NET 请求提早返回的罕见情况之一。你可以看到我的blog post on the subject一些有用的代码。

所以,像这样(简化为只在每个位置查找一个“有趣的地方”):

public async Task<PlaceWithData> FindPlaceAsync(Location myLocation) 
{ 
  Place place = await GetPlaceFromFoursquareAsync(myLocation); 
  PlaceWithData ret = await GetExtraDataFromDatabaseAsync(place); 
  if (ret.NeedsRefresh) 
    BackgroundTaskManager.Run(() => UpdateDatabaseAsync(place, ret)); 
  return ret; 
} 

您可能还想考虑扩展 ASP.NET 缓存系统,而不是“滚动您自己的”缓存。