首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#地铁程序不使用异步和StorageFiles响应

C#地铁程序不使用异步和StorageFiles响应
EN

Stack Overflow用户
提问于 2014-06-14 20:36:19
回答 1查看 43关注 0票数 0

我有一个程序,它获取一个文件并将其内容列出到一个字典中(好吧,列出.txt文件,然后再翻译成字典)。但是当它应该这样做的时候,程序就冻结了,没有响应,但是VS2013没有显示出任何问题。就像它的无限循环。我正在使用一些异步方法,我想我犯了某种严重的错误。

下面是一些代码(入口点在GamePage中,在OnNavigatedTo中):

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-14 20:49:23

问题就在这一行上:

代码语言:javascript
复制
ListQuestions().Result;

ListQuestions()返回之前,您将阻塞主线程,但是异步文件操作需要完成此线程。考虑将其改为:

代码语言:javascript
复制
await ListQuestions();

并向上传播async方法修饰符。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24224072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档