【问题标题】:Returning a HTTP response data from a function in a multithreaded manner (C# / VB )以多线程方式从函数返回 HTTP 响应数据(C#/VB)
【发布时间】:2016-11-03 15:53:41
【问题描述】:

我知道IAsyncResult 方法,但是根据我的实验,这仍然会暂时冻结用户界面 - 这对我来说很奇怪。我在 Google 上搜索了很多,但我似乎找不到一种不会让 UI 冻结的方法来实现它。

我想要一个函数以线程方式从HttpWebReqeust 返回数据。我需要一个好方法来做到这一点,而不是线程化,然后将一些变量设置为 true 并将响应存储在共享变量中。

有什么办法吗?

【问题讨论】:

标签: c# vb.net multithreading http webrequest


【解决方案1】:

您在 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();

您可以在此处看到等待执行完成的阻塞等待。因此,对于获得HttpResponseasync 方法,您可以轻松地使用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

【讨论】:

    猜你喜欢
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多