try...finally的妙用

受博文 C#中Finally的一个不太常见的用法 的启发,正好在开发中遇到这样一段代码:

public bool ChangeBlogApp(Guid userID, string oldBlogApp, string newBlogApp)
{
    CacheFactory.Default.Remove(CacheKeyManager.GetBlogConfigCacheKey(oldBlogApp));
    CacheFactory.Default.Remove(CacheKeyManager.GetBlogConfigCacheKey(newBlogApp));
    return _bcProvider.UpdateBlogApp(userID, newBlogApp);
}

需要把2行CacheFactory.Default.Remove的代码移至_bcProvider.UpdateBlogApp之后。

按照以前的做法,代码会改成这样(增加一个局部变量):

public bool ChangeBlogApp(Guid userID, string oldBlogApp, string newBlogApp)
{
    var result = _bcProvider.UpdateBlogApp(userID, newBlogApp);
    CacheFactory.Default.Remove(CacheKeyManager.GetBlogConfigCacheKey(oldBlogApp));
    CacheFactory.Default.Remove(CacheKeyManager.GetBlogConfigCacheKey(newBlogApp));
    return result;
}

而使用try...finally,可以无需增加局部变量,代码如下:

public bool ChangeBlogApp(Guid userID, string oldBlogApp, string newBlogApp)
{
    try
    {
        return _bcProvider.UpdateBlogApp(userID, newBlogApp);
    }
    finally
    {
        CacheFactory.Default.Remove(CacheKeyManager.GetBlogConfigCacheKey(oldBlogApp));
        CacheFactory.Default.Remove(CacheKeyManager.GetBlogConfigCacheKey(newBlogApp));
    }
}
posted @ 2014-04-15 12:16  dudu  阅读(2705)  评论(7编辑  收藏  举报