public static WebResponse GetResponseNoEx(this WebRequest req)
        {
            WebResponse      result        = null;
            ManualResetEvent responseReady = new ManualResetEvent(false);

            AsyncCallback callback = new AsyncCallback(ar =>
            {
                //var request = (WebRequest)ar.AsyncState;
                result = req.EndGetResponseNoEx(ar);
                responseReady.Set();
            });

            var async = req.BeginGetResponse(callback, null);

            if (!async.IsCompleted)
            {
                //async.AsyncWaitHandle.WaitOne();
                // Not having thread affinity seems to work better with ManualResetEvent
                // Using AsyncWaitHandle.WaitOne() gave unpredictable results (in the
                // unit tests), when EndGetResponse would return null without any error
                // thrown
                responseReady.WaitOne();
                //async.AsyncWaitHandle.WaitOne();
            }

            return(result);
        }
Beispiel #2
0
        public static WebResponse GetResponseNoEx(this WebRequest req)
        {
            WebResponse      result        = null;
            ManualResetEvent responseReady = new ManualResetEvent(initialState: false);
            Exception        caught        = null;

            AsyncCallback callback = new AsyncCallback(ar =>
            {
                //var request = (WebRequest)ar.AsyncState;
                try
                {
                    result = req.EndGetResponseNoEx(ar);
                }
                catch (Exception ex)
                {
                    caught = ex;
                }
                finally
                {
                    responseReady.Set();
                }
            });

            var async = req.BeginGetResponse(callback, null);

            if (!async.IsCompleted)
            {
#if !PORTABLE45
                ThreadPool.RegisterWaitForSingleObject(async.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), req, req.Timeout, true);
#endif

                //async.AsyncWaitHandle.WaitOne();
                // Not having thread affinity seems to work better with ManualResetEvent
                // Using AsyncWaitHandle.WaitOne() gave unpredictable results (in the
                // unit tests), when EndGetResponse would return null without any error
                // thrown
                responseReady.WaitOne();
                //async.AsyncWaitHandle.WaitOne();
            }

            if (caught != null)
            {
                throw caught;
            }

            return(result);
        }