How can I keep a WPF Image from blocking if the ImageSource references an unreachable Url?

后端 未结 2 1322
闹比i
闹比i 2021-01-12 10:01

I\'m writing a WPF application and trying to bind an image to my view model with the following XAML:



        
2条回答
  •  有刺的猬
    2021-01-12 10:19

    Well I think I found out why it is happening...

    I dug around with Reflector a bit to try to find out what exactly was getting called. Inside the BitmapDecoder I found a simple call to a WebRequest.BeginGetResponseStream.

    I wrote a quick console app to test:

    static void Main(string[] args)
    {
        DateTime start = DateTime.Now;
    
        WebRequest request = WebRequest.Create("http://nonexistserver/myicon.jpg");
        IAsyncResult ar = request.BeginGetResponse((AsyncCallback)delegate(IAsyncResult result)
        {
            try
            {
                WebResponse response = request.EndGetResponse(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }, null);
    
        Console.WriteLine(DateTime.Now - start);
        ar.AsyncWaitHandle.WaitOne();
    
        Console.WriteLine("Done");
        Console.ReadKey();
    }
    

    Without Fiddler running, the output is 2-3 seconds. With Fiddler running, the output is ~.25 seconds.

    Doing some more digging, it looks like BeginGetResponse (which is what WPF is using under the hood) blocks until name resolution is complete.

    See this question: webrequest.begingetresponse is taking too much time when the url is invalid

    So I understand why the blocking occurs now, but I don't know a clean solution for my application. :(

提交回复
热议问题