简体   繁体   中英

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

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

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

It throws an ArgumentException. When I inspected the 's' variable, it said the AsyncWaitHandle gave a NotSupportedException.

My question is then, how can I make a proper Webrequest that would work on all platforms?

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

In my opinion, you'll need to use latest Asyc/Await concept to perform this task like 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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