以多线程方式从函数返回 HTTP 响应数据 (C# / VB )
Returning a HTTP response data from a function in a multithreaded manner (C# / VB )
我知道 IAsyncResult
方法,但是从我的实验来看,这仍然会暂时冻结 UI 一点 - 这对我来说很奇怪。我已经 Google 了很多,我似乎无法找到一种方法来实现这个不会冻结 UI 一点点。
我想要的是以线程方式从 HttpWebReqeust
获取 return 数据的函数。我需要一个好的方法来做到这一点,而不是线程化它,然后将一些变量设置为 true
并将响应存储在共享变量中。
有什么办法吗?
您从 MSDN 中提到的代码确实阻止了 UI,因为这些行:
Thread.Sleep(0);
Console.WriteLine("Main thread {0} does some work.",
Thread.CurrentThread.ManagedThreadId);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
您可以在此处看到阻塞等待执行完成。因此,对于获得 HttpResponse
的 async
方法,您可以轻松地使用 async/await
关键字和 dozens of the sample code:
// inside the method marked as async
// prepare the Web Request
Task<WebResponse> getResponseTask = req.GetResponseAsync();
WebResponse response = await getResponseTask;
// process your result in the same context which have fired the request
我知道 IAsyncResult
方法,但是从我的实验来看,这仍然会暂时冻结 UI 一点 - 这对我来说很奇怪。我已经 Google 了很多,我似乎无法找到一种方法来实现这个不会冻结 UI 一点点。
我想要的是以线程方式从 HttpWebReqeust
获取 return 数据的函数。我需要一个好的方法来做到这一点,而不是线程化它,然后将一些变量设置为 true
并将响应存储在共享变量中。
有什么办法吗?
您从 MSDN 中提到的代码确实阻止了 UI,因为这些行:
Thread.Sleep(0);
Console.WriteLine("Main thread {0} does some work.",
Thread.CurrentThread.ManagedThreadId);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
您可以在此处看到阻塞等待执行完成。因此,对于获得 HttpResponse
的 async
方法,您可以轻松地使用 async/await
关键字和 dozens of the sample code:
// inside the method marked as async
// prepare the Web Request
Task<WebResponse> getResponseTask = req.GetResponseAsync();
WebResponse response = await getResponseTask;
// process your result in the same context which have fired the request