C#控制台项目:File.Copy执行时循环显示动态更新提示
C#控制台复制文件时实现动态加载提示
问题描述
首次开发C#控制台项目,现有代码如下:
if (File.Exists(InstallFolder + StrFilename)) { Console.WriteLine("\r\nSQS App Found"); File.Delete(InstallFolder + StrFilename); Console.WriteLine("Updating the Quotation System, Please Wait..."); File.Copy(StrServerFolder + StrFilename, InstallFolder + StrFilename); Console.WriteLine("Done. Launching the SQS App..."); Thread.Sleep(2000); System.Diagnostics.Process.Start(InstallFolder + StrFilename); Environment.Exit(0); }
需要在File.Copy执行期间,循环在同一行依次显示并覆盖以下三个提示:
- "Updating the Quotation System, Please Wait."
- "Updating the Quotation System, Please Wait.."
- "Updating the Quotation System, Please Wait..."
直至复制完成。
解决方案
因为File.Copy是同步阻塞操作,所以需要用后台线程运行加载动画,主线程专注执行文件复制,通过布尔变量同步状态。以下是简洁的实现代码:
using System.Threading.Tasks; // ... 其他现有代码 ... if (File.Exists(InstallFolder + StrFilename)) { Console.WriteLine("\r\nSQS App Found"); File.Delete(InstallFolder + StrFilename); bool isCopyComplete = false; // 启动后台线程显示加载动画 var loadingTask = Task.Run(() => { var prompts = new[] { "Updating the Quotation System, Please Wait.", "Updating the Quotation System, Please Wait..", "Updating the Quotation System, Please Wait..." }; int index = 0; while (!isCopyComplete) { // 使用\r覆盖当前行,不换行 Console.Write("\r" + prompts[index]); index = (index + 1) % prompts.Length; Thread.Sleep(500); // 控制提示切换速度 } // 复制完成后清空当前行,避免残留 Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r"); }); try { // 执行文件复制操作 File.Copy(StrServerFolder + StrFilename, InstallFolder + StrFilename); } finally { // 标记复制完成,终止加载线程循环 isCopyComplete = true; // 等待加载线程完成收尾操作 loadingTask.Wait(); } Console.WriteLine("Done. Launching the SQS App..."); Thread.Sleep(2000); System.Diagnostics.Process.Start(InstallFolder + StrFilename); Environment.Exit(0); }
关键说明
- 后台线程:通过
Task.Run启动后台线程,避免阻塞主线程的文件复制操作,保证动画和复制同时进行。 - 行覆盖逻辑:使用
Console.Write("\r" + 内容),\r是回车符,会将光标移到当前行开头,从而覆盖之前的文本,实现同一行动态更新。 - 状态同步:
isCopyComplete布尔变量用于通知后台线程复制已完成,终止提示循环。 - 线程收尾:在
finally块中等待后台线程结束,确保控制台输出清理完成后再执行后续流程。
内容的提问来源于stack exchange,提问作者John G
相关产品推荐
相关产品推荐

