以多线程方式从函数返回HTTP响应数据(c# / VB)
本文关键字:数据 VB 响应 HTTP 方式 多线程 函数 返回 | 更新日期: 2023-09-27 18:16:05
我知道IAsyncResult
的方法,但是从我的实验来看,这仍然会暂时冻结UI -这对我来说很奇怪。我已经谷歌了很多,我似乎找不到一种方法来实现这一点,不冻结UI一点。
我想要的是一个函数以线程方式从HttpWebReqeust
返回数据。我需要一个很好的方法来做到这一点,而不是线程化它,然后设置一些变量到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();
你可以在这里看到阻塞等待执行完成。因此,对于async
方式获得HttpResponse
,您可以轻松使用async/await
关键字,并使用数十个示例代码:
// 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