Search code examples
c#portable-class-libraryasync-await

Exception using await HttpClient.GetAsync in Portable Class Library


I have Portable Class Library(net40+sl4+win8+wp71) with code:

    public static async Task<Dictionary<string, FeedItem>> GetFeeds()  
    {  
        try
        {
            string data;
            using (HttpMessageHandler handler = new HttpClientHandler())
            {
                using (HttpClient httpClient = new HttpClient(handler))
                {
                    data = await httpClient.GetStringAsync(FeedsUrl + Guid.NewGuid()).ConfigureAwait(false);
                }
            }

            if (data != null)
            {
                //...
            }
            return null;
        }
        catch
        {
            return null;
        }
    }

Microsoft.Bcl, Microsoft.Bcl.Async and Microsoft.Net.Http are referenced.

I use this library in Windows 8 Metro app. Then I debugg app through VS2012, it is ok. But when I create App Package and install it, the app crashes on first launch everytime with error:

Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Runtime.InteropServices.COMException
Stack:
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__1(System.Object)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Edit: If I comment line "data = await httpClient.GetStringAsync" it will work without exception.

On second launch it always works.

Any suggestion?


Solution

  • I've figured it out. I use MVVM Light, so I have ViewModelLocator with code:

    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
    
        SimpleIoc.Default.Register<MainViewModel>(true);
    }
    

    So when I removed immediate creation of the model it stopped crashing:

    SimpleIoc.Default.Register<MainViewModel>(/*true*/);
    

    I have no idea why but I think it's because MVVM Light has some problems with Microsoft.Bcl, Microsoft.Bcl.Async or Microsoft.Net.Http.

    Hope this will help someone, e.g. this question