Search code examples
c#multithreadingasynchronouswindows-8windows-runtime

Running Async Method in Loop without Stackoverflow Exception


This piece of code keeps throwing a stackoverflow exception and I have a feeling it's either because of the await keyword causing the stack to fill up, or a thread availability issue. However, I'm not sure what the best way of remedying this would be.

The results variable is just a collection of StorageFiles and if it's above 1020 or so, the exception is thrown; otherwise it's usually fine.

private async void GetMusicTest()
{
    var sfolder = await StorageFolder.GetFolderFromPathAsync(dir);

    var query =  sfolder.CreateFileQueryWithOptions(queryOptions);

    var results = await query.GetFilesAsync();

    for (int i = 0; i < results.Count; i++)
    {
        MusicProperties mp = await results[i].Properties.GetMusicPropertiesAsync();
        Debug.WriteLine(mp.Title);
    }
}

This code works fine in a console application, but the error is thrown when used in a desktop WinForm app.

Interestingly, if result.Count() is used instead, then the error is thrown after three iterations, whereas results.Count throws it after iterating through at least half of the collection, if not all (it seems to vary). They both return the same values. What's the best way looping through without causing a stackoverflow exception or using up all available threads?


Solution

  • I think this is a bug that should be addressed.

    If I'm right, you can work around it by occasionally doing an await Task.Yield() within your loop.