C#在函数执行时填写进度条

时间:2017-01-22 16:34:31

标签: c#

我目前正在尝试阅读文本文件并提取其中的所有电子邮件地址。使用以下功能:

我的C#功能:

public void extractMails(string filePath)
{
    List<string> mailAddressList = new List<string>();

    string data = File.ReadAllText(filePath);
    Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
    MatchCollection emailMatches = emailRegex.Matches(data);

    StringBuilder sb = new StringBuilder();

    foreach (Match emailMatch in emailMatches)
    {
        sb.AppendLine(emailMatch.Value);
    }

    string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;
    string dirPath = Path.GetDirectoryName(exePath);

    File.WriteAllText(dirPath + "extractedEmails.txt", sb.ToString());
}

现在我添加了一个进度条,因为加载的文本文件可能很大。如果执行该功能,我怎样才能填充进度条,最后将进度条填充到100%?

我会感激任何帮助。

2 个答案:

答案 0 :(得分:0)

您只需遍历文件中所需的所有对象。您需要其中的对象数量,然后将当前迭代器乘以100除以对象的总量。这是你的意志。现在用你得到的值更新栏的过程。

答案 1 :(得分:0)

@ user3185569评论是正确的。我提供了一种不同类型的解决方案,而不使用asyncawait,以防您使用旧版本的Visual Studio。

基本上,您需要在新线程中完成任务,然后使用Invoke()更新进度条。这是一个简单的例子:

private int _progress;
private delegate void Delegate();

private void btnStartTask_Click(object sender, EventArgs e)
{
    // Initialize progress bar to 0 and task a new task
    _progress = 0;
    progressBar1.Value = 0;
    Task.Factory.StartNew(DoTask);
}

private void DoTask()
{
    // Simulate a long 5 second task
    // Obviously you'll replace this with your own task
    for (int i = 0; i < 5; i++)
    {
        System.Threading.Thread.Sleep(1000);
        _progress = (i + 1)*20;
        if (progressBar1.InvokeRequired)
        {
            var myDelegate = new Delegate(UpdateProgressBar);
            progressBar1.Invoke(myDelegate);
        }
        else
        {
            UpdateProgressBar();
        }
    }
}

private void UpdateProgressBar()
{
    progressBar1.Value = _progress;
}
相关问题