将 WebClient.DownloadStringAsync 封装成函数返回字符串
我有一个方法下载一个字符串,解析它,然后将解析后的数据作为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法将同步代码无缝转换为异步代码。在您的示例中,您应该返回 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.
您应该更改方法以通过
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 astring[]
into the method that handles theDownloadStringAsyncCompleted
event.尝试 WebClient.DownloadString 它不是异步的。
如果您想使用 DownloadStringAsync 方法,您需要等到 DownloadStringAsyncCompleted 事件触发。再次,这将是同步方法。如果您确实希望结果继续,请使用同步方法。
try WebClient.DownloadString it is not async.
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.