简体   繁体   English

进度栏未使用BackgroundWorker更新

[英]Progress Bar not updating using BackgroundWorker

I'm trying to read a file and display the progress on the screen. 我正在尝试读取文件并在屏幕上显示进度。 It should be displayed on a Progress Bar (progress) and a textbox (progress_text). 它应该显示在进度栏(progress)和文本框(progress_text)上。

This is the code I'm using: 这是我正在使用的代码:

public partial class MainWindow : Window
{
    public static List<String> file = new List<String>();
    public long currentPosition = 0;
    String line;
    long length;
    public BackgroundWorker worker = new BackgroundWorker();


    public MainWindow()
    {
        InitializeComponent();

        worker.WorkerReportsProgress = true;
        worker.DoWork += worker_DoWork;
        worker.ProgressChanged += worker_ProgressChanged;
    }

    private void Start(object sender, RoutedEventArgs e)
    {
        worker.RunWorkerAsync();
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker bg = sender as BackgroundWorker;

        Dispatcher.Invoke(() =>
        {
            progress.Minimum = 0;
            progress.Maximum = 100;

            FileInfo fi = new FileInfo(upload.Text);
            length = fi.Length;

            int percent;


            using (StreamReader sr = new StreamReader(upload.Text, System.Text.Encoding.ASCII))
            {
                while (sr.EndOfStream == false)
                {
                    line = sr.ReadLine();
                    file.Add(line);
                    currentPosition += line.Count();

                    percent = (int)(100.0 / length * currentPosition);
                    bg.ReportProgress(percent);
                }
            }
        });
    }

    void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progress.Value = e.ProgressPercentage;
        progress_text.Text = "reading " + currentPosition + " out of " + length;
    }
}

XAML: XAML:

<Window x:Class="ProgressBarUploadFile.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    >
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="20*"/>
        <RowDefinition Height="20*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="20*"/>
        <ColumnDefinition Width="20*"/>
    </Grid.ColumnDefinitions>
    <Button Grid.Row="0" Grid.Column="0" Content="Select File" FontSize="15" Click="Upload_file"/>
    <TextBox x:Name="upload" Grid.Row="0" Grid.Column="1" Text="" />
    <Button Grid.Row="1" Grid.Column="0" Content="Start upload" FontSize="15" Click="Start"/>
    <ProgressBar Name="progress" Grid.Row="1" Grid.Column="1" />
    <TextBlock Name="progress_text" Grid.Row="1" Grid.Column="1" VerticalAlignment="Bottom"/>
</Grid>

When I run it in debug, it seems to be working. 当我在调试中运行它时,它似乎正在工作。 But the progress bar and textbox are updated only when the file is read completely. 但是,只有在完全读取文件后,进度条和文本框才会更新。

I followed a few tutorials, such as: 我遵循了一些教程,例如:

https://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx?f=255&MSPPError=-2147217396 https://msdn.microsoft.com/zh-cn/library/cc221403%28v=vs.95%29.aspx?f=255&MSPPError=-2147217396

http://www.wpf-tutorial.com/misc-controls/the-progressbar-control/ http://www.wpf-tutorial.com/misc-controls/the-progressbar-control/

But I can't figure it out.. 但我不知道。

I think it's something very small, but I can't find it. 我认为它很小,但是我找不到。

Thank you! 谢谢!

Try this code: 试试这个代码:

private void Start(object sender, RoutedEventArgs e)
    {
 progress.Minimum = 0;
            progress.Maximum = 100;
        worker.RunWorkerAsync();
    }



BackgroundWorker bg = sender as BackgroundWorker;
            FileInfo fi = new FileInfo(@"File");
            length = fi.Length;

            int percent;


            using (StreamReader sr = new StreamReader(@"File", System.Text.Encoding.ASCII))
            {
                while (sr.EndOfStream == false)
                {
                    line = sr.ReadLine();
                    file.Add(line);
                    currentPosition += line.Count();

                    percent = (int)(currentPosition / length) * 100;
                    bg.ReportProgress(percent);
                    Thread.Sleep(100);
                }
            }

Your code has this problem: 您的代码有此问题:

(int)(a / b) * 100 will calculate a/b first then convert it to int and then *100 , so before a reaches b , the a/b will always be 0.* and (int)(a/b) will always be 0 so the final value 0*100 will always be 0. (int)(a / b) * 100将首先计算a/b然后将其转换为int然后*100 ,因此在a到达b之前, a/b始终为0.*(int)(a/b)始终为0因此最终值0*100始终为0。

Suddenly when a=b then (int)(a/b) become 1 and the final value changed to 100. That is why your progress bar will not be updated until the file is read completely 突然,当a=b (int)(a/b)变为1 ,最终值更改为100。这就是为什么直到完全读取文件后才会更新进度栏的原因

So, you should use percent = (int)(currentPosition * 100 / length); 因此,您应该使用percent = (int)(currentPosition * 100 / length);

Or as @jmc suggested in the comment: use percent = (int)(100.0 / length * currentPosition); 或如@jmc在注释中建议的那样:使用percent = (int)(100.0 / length * currentPosition);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM