使用异常等待HttpClient.GetAsync便携式类库 [英] Exception using await HttpClient.GetAsync in Portable Class Library
问题描述
我有便携式类库(net40 + SL4 + win8的+ wp71)与code:结果
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和Microsoft.Net.Http参考。
Microsoft.Bcl, Microsoft.Bcl.Async and Microsoft.Net.Http are referenced.
我使用Windows 8地铁应用这个库。然后,我通过VS2012 debugg的应用程序,它是确定。但是,当我创建应用程序包并安装它,第一次启动每次应用程序崩溃与错误:
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()
编辑:如果我评论在线数据=等待httpClient.GetStringAsync这将无一例外工作。
If I comment line "data = await httpClient.GetStringAsync" it will work without exception.
在第二次发射它总是有效。
On second launch it always works.
任何建议?
推荐答案
我已经想通了。我使用MVVM轻,所以我必须用ViewModelLocator code:结果
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*/);
我不知道为什么,但我认为这是因为MVVM光有一些问题,Microsoft.Bcl,Microsoft.Bcl.Async或Microsoft.Net.Http。
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.
希望这会帮助别人,例如<一href=\"http://stackoverflow.com/questions/14960268/await-with-httpclient-getasyncurl-and-getting-error-system-nullreferenceexcept\">this问题
Hope this will help someone, e.g. this question
这篇关于使用异常等待HttpClient.GetAsync便携式类库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!