避免竞争条件创建StorageFolder

时间:2013-01-12 15:29:27

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

我正在测试一个新的Win8商店应用程序,并注意到我想避免的竞争条件。所以我正在寻找一种避免这种竞争条件的方法。

我有一个类,在实例化时会调用一个方法来确保它有一个本地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");

    }

1 个答案:

答案 0 :(得分: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");
    }