gpt4 book ai didi

c# - 从 Internet 下载大文件时,如何阻止 C# 应用程序的 UI 变得无响应

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:56 25 4
gpt4 key购买 nike

我已经创建了一个 C# WPF 应用程序。在我的代码中,我使用 WebClient.DownloadFile() 从互联网上下载了一个大文件。

当我这样做时,应用程序的 UI 变得没有响应(应用程序不会卡住,如果我离开它足够长的时间它会下载并恢复正常)。

代码本身在另一个脚本中,从 UI 线程调用。阻止 UI 变得无响应的最佳方法是什么?

最佳答案

使用 WebClient.DownloadFileAsync方法在工作线程中下载文件。 UI 线程将在此过程中保持响应。

方法文档很好地解释了它:

This method downloads the resource at the URI specified by in the address parameter. When the download completes successfully, the downloaded file is named fileName on the local computer. The file is downloaded asynchronously using thread resources that are automatically allocated from the thread pool. To receive notification when the file is available, add an event handler to the DownloadFileCompleted event.

This method does not block the calling thread while the resource is being downloaded. To block while waiting for the download to complete, use one of the DownloadFile methods.

You can use the CancelAsync method to cancel asynchronous operations that have not completed.

关于c# - 从 Internet 下载大文件时,如何阻止 C# 应用程序的 UI 变得无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47926497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com