gpt4 book ai didi

c# - 避免竞争条件创建 StorageFolder

转载 作者:太空宇宙 更新时间:2023-11-03 13:49:03 26 4
gpt4 key购买 nike

我正在对一个新的 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");

}

最佳答案

正如 Iboshuizen 所建议的,我会同步执行此操作。这可以通过 asynctaskawait 来完成。有一个陷阱 - 无法在 Class1 的构造函数内完成设置,因为构造函数不支持异步/等待。因此 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");
}

关于c# - 避免竞争条件创建 StorageFolder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14294803/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com