0

I have a program, which gets a file and lists its content to a dictionary (well, lists .txt files which then are translated to a dictionary). But when it's suppose to do that the program freezes and doesn't respond, but VS2013 doesn't show any problem. Like its in infinite loop. I'm using some async methods, I suppose I made some kind of crucial mistake.

Here is some code (entry point is in GamePage, in 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);
    }
}
user3212350
  • 401
  • 1
  • 6
  • 18
  • 1
    I think you have a deadlock - http://stackoverflow.com/questions/15021304/an-async-await-example-that-causes-a-deadlock – Daniel Kelley Jun 14 '14 at 20:43
  • The last instruction is does is : `return await folder.GetFilesAsync();` in `FileParse` class. I'm not sure how to get rid of this bug – user3212350 Jun 14 '14 at 20:52

1 Answers1

2

The problem is in this line:

ListQuestions().Result;

You are blocking the main thread until ListQuestions() returns, but the async file operation need this thread to complete. Consider changing this to:

await ListQuestions();

And propagate the async method modifier all the way up.

qbik
  • 5,502
  • 2
  • 27
  • 33