简体   繁体   English

将可移植类库与Webrequest和WP8一起使用

[英]Using Portable Class Library with Webrequest and WP8

I have a problem to which I can't find any solution, and I find it hard to believe I'm the only one getting this error. 我有一个我找不到任何解决方案的问题,而且我很难相信我是唯一遇到此错误的人。

I have this piece of C# code in a Portable Class Library 我在可移植类库中有这段C#代码

static public void GetAnimeListFromWeb(ObservableCollection<AnimeViewModel> collection, string Url, string encodedLogin = "")
    {
        WebRequest request = WebRequest.Create(Url);
        request.Headers["Authorization"] = encodedLogin;

        IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback( s => {
            WebResponse response = (s.AsyncState as WebRequest).EndGetResponse(s);
            XDocument doc = XDocument.Load(response.GetResponseStream());

            IEnumerable<AnimeViewModel> result = ParseAnimeXML(doc);

            collection = (ObservableCollection<AnimeViewModel>)result;

        }), request);
    }

When I compile this, it builds, and the code also works in a small console program I wrote to test it. 当我对此进行编译时,它会生成,并且代码也可以在我编写的用于测试它的小型控制台程序中使用。 However, when testing in a Windows Phone 8 app it crashes on 但是,在Windows Phone 8应用中进行测试时,它会崩溃

WebResponse response = (s.AsyncState as WebRequest).EndGetResponse(s);

It throws an ArgumentException. 它抛出一个ArgumentException。 When I inspected the 's' variable, it said the AsyncWaitHandle gave a NotSupportedException. 当我检查's'变量时,它说AsyncWaitHandle给出了NotSupportedException。

My question is then, how can I make a proper Webrequest that would work on all platforms? 我的问题是,我怎样才能做出适合所有平台的Webrequest?

EDIT: Maybe it is useful to note that I'm targeting .NET 4.5, SL4 and higher, WP7 and higher and .NET for Windows Store Apps 编辑:也许有用的是,我针对Windows Store Apps针对.NET 4.5,SL4和更高版本,WP7和更高版本以及.NET

In my opinion, you'll need to use latest Asyc/Await concept to perform this task like DownloadStringAsync. 我认为,您需要使用最新的Asyc / Await概念来执行此任务,例如DownloadStringAsync。 Because Async/Await is the only supported mechanism in Windows 8 and Windows Phone 8. However, when you use this code and build it for multiple platforms, compiler will handle the intricacies of different platform and produce the required code. 因为Async / Await是Windows 8和Windows Phone 8中唯一受支持的机制,但是,当您使用此代码并将其构建用于多个平台时,编译器将处理不同平台的复杂性并生成所需的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM