6

我已将旧的 HttpHandler (.ashx) TwitterFeed 代码移植到 WebAPI 应用程序。代码的核心使用了优秀的 Linq2Twitter 包 ( https://linqtotwitter.codeplex.com/ )。移植的一部分涉及将此组件从版本 2 升级到版本 3,它现在提供了许多异步方法调用——这对我来说是新的。这是基本的控制器:

public async Task<IEnumerable<Status>> 
GetTweets(int count, bool includeRetweets, bool excludeReplies)
{
   var auth = new SingleUserAuthorizer
   {
      CredentialStore = new SingleUserInMemoryCredentialStore
      {
         ConsumerKey       = ConfigurationManager.AppSettings["twitterConsumerKey"],
         ConsumerSecret    = ConfigurationManager.AppSettings["twitterConsumerKeySecret"],
         AccessToken       = ConfigurationManager.AppSettings["twitterAccessToken"],
         AccessTokenSecret = ConfigurationManager.AppSettings["twitterAccessTokenSecret"]
      }
   };

   var ctx = new TwitterContext(auth);

   var tweets =
      await
      (from tweet in ctx.Status
         where (
            (tweet.Type == StatusType.Home)
            && (tweet.ExcludeReplies == excludeReplies)
            && (tweet.IncludeMyRetweet == includeRetweets)
            && (tweet.Count == count)
         )
      select tweet)
      .ToListAsync();

   return tweets;
}

这很好用,但以前,我缓存了结果以避免“过度调用”Twitter API。正是在这里,我遇到了一个问题(更多是因为我对异步协议缺乏了解,而不是我怀疑的其他任何事情)。

总而言之,我要做的是首先检查缓存,如果数据不存在,则重新水化缓存并将数据返回给调用者(网页)。这是我对代码的尝试

public class TwitterController : ApiController {

   private const string CacheKey = "TwitterFeed";

   public async Task<IEnumerable<Status>>
   GetTweets(int count, bool includeRetweets, bool excludeReplies)
   {
      var context = System.Web.HttpContext.Current;
      var tweets = await GetTweetData(context, count, includeRetweets, excludeReplies);
      return tweets;
   }

   private async Task<IEnumerable<Status>>
   GetTweetData(HttpContext context, int count, bool includeRetweets, bool excludeReplies)
   {
      var cache = context.Cache;
      Mutex mutex = null;
      bool iOwnMutex = false;
      IEnumerable<Status> data = (IEnumerable<Status>)cache[CacheKey];

      // Start check to see if available on cache
      if (data == null)
      {
         try
         {
            // Lock base on resource key
            mutex = new Mutex(true, CacheKey);

            // Wait until it is safe to enter (someone else might already be
            // doing this), but also add 30 seconds max.
            iOwnMutex = mutex.WaitOne(30000);

            // Now let's see if some one else has added it...
            data = (IEnumerable<Status>)cache[CacheKey];

            // They did, so send it...
            if (data != null)
            {
               return data;
            }

            if (iOwnMutex)
            {
               // Still not there, so now is the time to look for it!
               data = await CallTwitterApi(count, includeRetweets, excludeReplies);

               cache.Remove(CacheKey);
               cache.Add(CacheKey, data, null, GetTwitterExpiryDate(),
                  TimeSpan.Zero, CacheItemPriority.Normal, null);
            }
         }
         finally
         {
            // Release the Mutex.
            if ((mutex != null) && (iOwnMutex))
            {
               // The following line throws the error:
               // Object synchronization method was called from an
               // unsynchronized block of code.
               mutex.ReleaseMutex();
            }
         }
      }

      return data;
   }

   private DateTime GetTwitterExpiryDate()
   {
      string szExpiry = ConfigurationManager.AppSettings["twitterCacheExpiry"];
      int expiry = Int32.Parse(szExpiry);
      return DateTime.Now.AddMinutes(expiry);
   }

   private async Task<IEnumerable<Status>>
   CallTwitterApi(int count, bool includeRetweets, bool excludeReplies)
   {
      var auth = new SingleUserAuthorizer
      {
         CredentialStore = new SingleUserInMemoryCredentialStore
         {
            ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
            ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerKeySecret"],
            AccessToken = ConfigurationManager.AppSettings["twitterAccessToken"],
            AccessTokenSecret = ConfigurationManager.AppSettings["twitterAccessTokenSecret"]
         }
      };

      var ctx = new TwitterContext(auth);

      var tweets =
         await
         (from tweet in ctx.Status
          where (
             (tweet.Type == StatusType.Home)
             && (tweet.ExcludeReplies == excludeReplies)
             && (tweet.IncludeMyRetweet == includeRetweets)
             && (tweet.Count == count)
             && (tweet.RetweetCount < 1)
          )
          select tweet)
         .ToListAsync();

      return tweets;
   }

}

问题出现在发布 Mutex 的 finally 代码块中(尽管我担心 GetTweetData() 方法的整体模式和方法):

if ((mutex != null) && (iOwnMutex))
{
    // The following line throws the error:
    // Object synchronization method was called from an
    // unsynchronized block of code.
    mutex.ReleaseMutex();
}

如果我注释掉该行,则代码可以正常工作,但是(我假设)我应该释放创建它的 Mutex。据我所知,这个问题与创建和释放互斥锁之间的线程变化有关。

由于我缺乏异步编码方面的一般知识,我不确定a)我使用的模式是否可行,b)如果可行,我如何解决问题。

任何建议将不胜感激。

4

1 回答 1

5

使用这样的互斥锁是行不通的。一方面, aMutex是线程仿射的,因此它不能与async代码一起使用。

我注意到的其他问题:

  • Cache是线程安全的,因此无论如何它都不需要互斥锁(或任何其他保护)。
  • 异步方法应该遵循基于任务的异步模式

关于缓存有一个重要提示:当您只有一个内存缓存时,请缓存任务而不是结果数据。在旁注中,我不得不想知道是否HttpContext.Cache是最好的缓存,但我会保持原样,因为您的问题更多的是关于异步代码如何更改缓存模式。

所以,我推荐这样的东西:

private const string CacheKey = "TwitterFeed";

public Task<IEnumerable<Status>> GetTweetsAsync(int count, bool includeRetweets, bool excludeReplies)
{
  var context = System.Web.HttpContext.Current;
  return GetTweetDataAsync(context, count, includeRetweets, excludeReplies);
}

private Task<IEnumerable<Status>> GetTweetDataAsync(HttpContext context, int count, bool includeRetweets, bool excludeReplies)
{
  var cache = context.Cache;
  Task<IEnumerable<Status>> data = cache[CacheKey] as Task<IEnumerable<Status>>;
  if (data != null)
    return data;
  data = CallTwitterApiAsync(count, includeRetweets, excludeReplies);
  cache.Insert(CacheKey, data, null, GetTwitterExpiryDate(), TimeSpan.Zero);
  return data;
}

private async Task<IEnumerable<Status>> CallTwitterApiAsync(int count, bool includeRetweets, bool excludeReplies)
{
  ...
}

如果两个不同的请求(来自两个不同的会话)在相同的确切时间请求相同的 twitter 提要,那么提要将被请求两次的可能性很小。但我不会因此而失眠。

于 2014-03-19T22:53:28.567 回答