将 WebClient.DownloadStringAsync 封装成函数返回字符串

发布于 2024-12-14 07:22:03 字数 184 浏览 0 评论 0原文

我有一个方法下载一个字符串,解析它,然后将解析后的数据作为 string[] 返回。我现在想更改该方法,以便它使用 DownloadStringAsync,但我不知道如何仍然将其作为函数返回该字符串数组。

由于获取的字符串是在 DownloadStringAsyncCompleted 方法中解析的,而不是在从 :S 调用它的方法中解析的

I had a method downloading a string, parsing it and then returning the parsed data as a string[]. I now want to change that method so it uses the DownloadStringAsync, but I don't know how to still have it as a function return that string array.

Since the fetched string is parsed in the DownloadStringAsyncCompleted method and not in the method it was called from :S

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冰葑 2024-12-21 07:22:03

您无法将同步代码无缝转换为异步代码。在您的示例中,您应该返回 void 并接受另一个 Action 类型的参数(回调),您应该在 DownloadStringAsyncCompleted 中调用该参数来表示数据已到来。

C# 5 会对此有所帮助,但异步仍然是异步。

You cannot seamlessly transform synchronous code into asynchronous one. In your example, you should return void and accept another parameter of type Action (callback) that you should call in DownloadStringAsyncCompleted to signal that data has come.

C# 5 will help a little bit with that, but still async is async.

淡写薰衣草的香 2024-12-21 07:22:03

您应该更改方法以通过 DownloadStringAsync() 触发异步下载的开始。然后将解析它并返回 string[] 的代码移至处理 DownloadStringAsyncCompleted 事件的方法中。

You should change your method to trigger the start of the download Async via DownloadStringAsync(). Then move the code that parses it and returns a string[] into the method that handles the DownloadStringAsyncCompleted event.

美羊羊 2024-12-21 07:22:03

尝试 WebClient.DownloadString 它不是异步的。

WebClient client = new WebClient ();
string reply = client.DownloadString (address);
Console.WriteLine (reply);

如果您想使用 DownloadStringAsync 方法,您需要等到 DownloadStringAsyncCompleted 事件触发。再次,这将是同步方法。如果您确实希望结果继续,请使用同步方法。

try WebClient.DownloadString it is not async.

WebClient client = new WebClient ();
string reply = client.DownloadString (address);
Console.WriteLine (reply);

If you want to use DownloadStringAsync method you need to wait until DownloadStringAsyncCompleted event fired. again it going to be sync method. if you really want a result to continue then use sync method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文