gpt4 book ai didi

c# - 如何在 Windows 应用程序中显示进度条?

转载 作者:行者123 更新时间:2023-11-30 19:45:23 25 4
gpt4 key购买 nike

我正在使用 C# 开发 Windows 应用程序。

我有一个表单和一个包含所有方法的类。

我在类中有一个方法,我正在处理 arraylist 中的一些文件。我想为此文件处理调用进度条方法,但它不起作用。

任何帮助

PFB 我的代码片段:

public void TraverseSource()
{
string[] allFiles1 = Directory.GetFiles(sourcePath, "*.xml", SearchOption.AllDirectories);

var allFiles = new ArrayList();
var length = allFiles.Count;
foreach (string item in allFiles1)
{
if (!item.Substring(item.Length - 6).Equals("MD.xml"))
{
allFiles.Add(item);

// Here i want to invoke progress bar which is in form
}
}
}

最佳答案

您需要使用 BackgroundWorker组件,其中 DoWork 处理程序包含您的实际工作(string[] allFiles1 部分及以后)。它看起来像这样:

public void TraverseSource()
{
// create the BackgroundWorker
var worker = new BackgroundWorker
{
WorkerReportsProgress = true
};

// assign a delegate to the DoWork event, which is raised when `RunWorkerAsync` is called. this is where your actual work should be done
worker.DoWork += (sender, args) => {
string[] allFiles1 = Directory.GetFiles(sourcePath, "*.xml", SearchOption.AllDirectories);

var allFiles = new ArrayList();

foreach (var i = 0; i < allFiles1.Length; i++)
{
if (!item.Substring(item.Length - 6).Equals("MD.xml"))
{
allFiles.Add(item);
// notifies the worker that progress has changed
worker.ReportProgress(i/allFiles.Length*100);
}
}
};
// assign a delegate that is raised when `ReportProgress` is called. this delegate is invoked on the original thread, so you can safely update a WinForms control
worker.ProgressChanged += (sender, args) => {
progressBar1.Value = args.ProgressPercentage;
};

// OK, now actually start doing work
worker.RunWorkerAsync();

}

关于c# - 如何在 Windows 应用程序中显示进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10646575/

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