【问题标题】:Avoid Race Condition Creating StorageFolder避免竞争条件创建 StorageFolder
【发布时间】:2013-01-12 15:29:27
【问题描述】:

我正在对一个新的 Win8 Store 应用程序进行单元测试,并注意到我想避免的竞争情况。所以我正在寻找一种方法来避免这种竞争条件。

我有一个类,它在实例化时调用一个方法来确保它有一个本地 StorageFolder。我的单元测试只是实例化对象并测试文件夹是否存在。有时文件夹不是,有时它是,所以我认为这是一个竞争条件,因为 CreateFolderAsync 是异步的(显然)。

public class Class1
{
    StorageFolder _localFolder = null;

    public Class1()
    {
        _localFolder = ApplicationData.Current.LocalFolder;
        _setUpStorageFolders();
    }

    public StorageFolder _LocalFolder
    {
        get
        {
            return _localFolder;
        }

    }


    async void _setUpStorageFolders()
    {
        try
        {
            _localFolder = await _localFolder.CreateFolderAsync("TestFolder", CreationCollisionOption.FailIfExists);

        }
        catch (Exception)
        {
            throw;
        }
    }
}

我的单元测试如下所示:

 [TestMethod]
    public void _LocalFolder_Test()
    {
        Class1 ke = new Class1();


        // TODO: Fix Race Condition 
        StorageFolder folder = ke._LocalFolder;

        string folderName = folder.Name;

        Assert.IsTrue(folderName == "TestFolder");

    }

【问题讨论】:

  • 这是集合中唯一的测试吗?还有其他测试吗?如果是这样,您是否在每个人之间进行设置和清理?
  • 为什么要异步创建文件夹?这不是一个非常耗时的操作,会造成巨大的性能损失
  • 是的,现在只有一个测试。
  • 同步执行此操作的模式是什么?
  • 我的错,StorageFolder 只有异步方法 (msdn.microsoft.com/library/windows/apps/BR227230)

标签: c# windows-8 windows-store-apps


【解决方案1】:

正如 Iboshuizen 建议的那样,我会同步执行此操作。这可以通过asynctaskawait 完成。有一个问题 - 无法在 Class1 的构造函数中完成设置,因为构造函数不支持 async/await。因为这个SetUpStorageFolders 现在是公开的,并且是从测试方法中调用的。

public class Class1
{
    StorageFolder _localFolder = null;

    public Class1()
    {
        _localFolder = ApplicationData.Current.LocalFolder;
                // call to setup removed here because constructors
                // do not support async/ await keywords
    }

    public StorageFolder _LocalFolder
    {
        get
        {
            return _localFolder;
        }

    }

      // now public... (note Task return type)
    async public Task SetUpStorageFolders()
    {
        try
        {
            _localFolder = await _localFolder.CreateFolderAsync("TestFolder", CreationCollisionOption.FailIfExists);

        }
        catch (Exception)
        {
            throw;
        }
    }
}

测试:

 // note the signature change here (async + Task)
 [TestMethod]
    async public Task _LocalFolder_Test()
    {
        Class1 ke = new Class1();
        // synchronous call to SetupStorageFolders - note the await
        await ke.SetUpStorageFolders();

        StorageFolder folder = ke._LocalFolder;

        string folderName = folder.Name;

        Assert.IsTrue(folderName == "TestFolder");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-30
    • 2010-09-25
    • 2016-06-12
    • 2010-09-25
    • 2019-06-12
    • 1970-01-01
    • 2020-01-16
    相关资源
    最近更新 更多