Web项目中的线程安全文件访问?

时间:2014-08-18 23:49:21

标签: c# multithreading caching

我需要在Web项目中使用本地文件缓存。我正在测试 fc.codeplex.com 其中"是.Net Framework 4的System.Runtime.Caching.ObjectCache的具体实现,它使用本地文件系统作为目标位置"。在我们的测试中,它一直没有问题。我的问题是,如果您认为GetStream中的try-catch代码是线程安全的:

///AccessTimeout is a TimeSpan to optionally specify a timeout.

/// <summary>
/// This function servies to centralize file stream access within this class.
/// </summary>
/// <param name="path"></param>
/// <param name="mode"></param>
/// <param name="access"></param>
/// <returns></returns>
private FileStream GetStream(string path, FileMode mode, FileAccess access)
{
    FileStream stream = null;
    TimeSpan interval = new TimeSpan(0, 0, 0, 0, 50);
    TimeSpan totalTime = new TimeSpan();
    while (stream == null)
    {
        try
        {
            stream = File.Open(path, mode, access);
        }
        catch (IOException ex)
        {
            Thread.Sleep(interval);
            totalTime += interval;

            //if we've waited too long, throw the original exception.
            if (AccessTimeout.Ticks != 0)
            {
                if (totalTime > AccessTimeout)
                {
                    throw ex;
                }
            }
        }
    }
    return stream;
}

0 个答案:

没有答案