积极答复者
Win8异步读写文件问题

问题
-
在Win8提供的API里面,对于文件的读写都是采用异步的方式。现在我需要等待文件读写完成,并将读取的文件内容保存到变量中,以供后面使用。但是还未等我将内容保存到变量中,程序就往下面执行了,这时变量还没有值,请问应该要怎样做,让变量赋值完成再往下走。相关的代码如下。
private ushort[] testArray = new ushort[0xffff]; public static Test() { LoadFile(); //下面需要使用testArray变量,但是此时变量还没有值
} public async static void LoadFile() { StorageFolder packageFolder = Package.Current.InstalledLocation; StorageFile packagedFile = await packageFolder.GetFileAsync(@"test.bin"); using (Stream stream = await packagedFile.OpenStreamForReadAsync()) { using (BinaryReader reader = new BinaryReader(stream)) { for (int i = 0; i < 0xffff; i++) { testArray[i] = reader.ReadUInt16(); } } } }
- 已编辑 WinRT开发 2013年2月20日 8:44
答案
-
???
- 已标记为答案 WinRT开发 2013年2月20日 8:58
- 取消答案标记 WinRT开发 2013年2月20日 9:08
- 已建议为答案 Aaron XueModerator 2013年2月21日 9:27
- 已标记为答案 Aaron XueModerator 2013年3月4日 9:15
- 已编辑 Shi Xin 2016年5月16日 9:07
-
public async Task Init()...
使用时,先确保await Test.Init(),再访问相关数据.
- 已建议为答案 Aaron XueModerator 2013年2月21日 9:27
- 已标记为答案 Aaron XueModerator 2013年3月4日 9:15
全部回复
-
???
- 已标记为答案 WinRT开发 2013年2月20日 8:58
- 取消答案标记 WinRT开发 2013年2月20日 9:08
- 已建议为答案 Aaron XueModerator 2013年2月21日 9:27
- 已标记为答案 Aaron XueModerator 2013年3月4日 9:15
- 已编辑 Shi Xin 2016年5月16日 9:07
-
public async Task Init()...
使用时,先确保await Test.Init(),再访问相关数据.
- 已建议为答案 Aaron XueModerator 2013年2月21日 9:27
- 已标记为答案 Aaron XueModerator 2013年3月4日 9:15
-
Hi,
你需要使用await。因此不能够把这个语句放在构造函数中。你需要新建一个async方法在构造函数中调用。
Aaron
MSDN Community Support | Feedback to us
Develop and promote your apps in Windows Store
Please remember to mark the replies as answers if they help and unmark them if they provide no help. -
Hi,
你需要使用await。因此不能够把这个语句放在构造函数中。你需要新建一个async方法在构造函数中调用。
Aaron
MSDN Community Support | Feedback to us
Develop and promote your apps in Windows Store
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
你好,我按照你说的试了下,还是不行,不知道为什么。
public static Test()
{
Init(); //下面需要使用testArray变量,但是此时变量还没有值
}
public async void Init()
{
await LoadFile();
}