我有一个程序,它获取一个文件并将其内容列出到一个字典中(好吧,列出.txt文件,然后再翻译成字典)。但是当它应该这样做的时候,程序就冻结了,没有响应,但是VS2013没有显示出任何问题。就像它的无限循环。我正在使用一些异步方法,我想我犯了某种严重的错误。
下面是一些代码(入口点在GamePage中,在OnNavigatedTo中):
public sealed partial class GamePage : Page
{
List<Question> Questions;
public GamePage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
StartGame();
}
private void StartGame()
{
Questions = new FileParse(MainPage.folder).GetQuestions();
}
}
class FileParse
{
List<Question> Questions;
IReadOnlyList<StorageFile> fileList;
private StorageFolder folder;
public FileParse(StorageFolder folder)
{
this.folder = folder;
Questions = new List<Question>();
}
public List<Question> GetQuestions()
{
fileList =ListQuestions().Result;
foreach (StorageFile file in fileList)
{
AddQuestion(file);
}
return Questions;
}
private async Task<IReadOnlyList<StorageFile>> ListQuestions()
{
return await folder.GetFilesAsync();
}
private async void AddQuestion(StorageFile file)
{
IList<string> text = await FileIO.ReadLinesAsync(file);
Question current = new Question();
string ans = text[0];
for(int i=1; i<ans.Length; i++)
{
current.AddAnswer(text[i], ans[i]==1?true:false);
}
Questions.Add(current);
}
}
class Question
{
private Dictionary<string, bool> answers;
public int QuestionCounter { get; set; }
public Question()
{
answers = new Dictionary<string, bool>();
}
public void AddAnswer(string content, bool isRight)
{
answers.Add(content, isRight);
}
}发布于 2014-06-14 20:49:23
问题就在这一行上:
ListQuestions().Result;在ListQuestions()返回之前,您将阻塞主线程,但是异步文件操作需要完成此线程。考虑将其改为:
await ListQuestions();并向上传播async方法修饰符。
https://stackoverflow.com/questions/24224072
复制相似问题