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

标签 c# wpf

我已经创建了一个 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/

相关文章:

c# - 为什么我可以在 C# 中编写一个什么都不做的通用 catch 语句?

c# - 奇怪的 WPF DataGrid 问题

c# - WPF TreeView 泄漏所选项目

c# - ListView 上的工具提示

javascript - 如何从c#wpf调用js函数

c# - 为什么这个 C# 代码这么慢?优化目录/文件搜索和添加所需

c# - Serilog:如何进一步增强 appsettings.json 中的过滤器表达式?

c# - 是否可以使用c#将结构存储在文本文件中

c# - 将 DataSource 属性添加到自定义 WinForms 控件

c# - 我想强制渲染,但尽可能快地绘制 (InvalidateVisual/CompositionTarget.Rendering)