Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Progressbar不移动(WinForms、.Net和BackgroundWorker) 介绍_C#_.net_Winforms_Progress Bar - Fatal编程技术网

C# Progressbar不移动(WinForms、.Net和BackgroundWorker) 介绍

C# Progressbar不移动(WinForms、.Net和BackgroundWorker) 介绍,c#,.net,winforms,progress-bar,C#,.net,Winforms,Progress Bar,我正在尝试使用.Net制作一个WinForms应用程序 我使用的教程显示了BackgroundWorker和ProgressBar集成 我在表单中添加了ProgressBar和BackgroundWorker控件。 这些名称与示例中的名称相同。另外,我将BackgroundWorker的WorkerReportProgress属性设置为True。未显示任何错误,项目已成功编译 问题 问题是-progressbar不移动。 然而,当手动单击时,它会移动progressBar1.PerformSte

我正在尝试使用
.Net
制作一个
WinForms
应用程序

我使用的教程显示了
BackgroundWorker
ProgressBar
集成

我在表单中添加了
ProgressBar
BackgroundWorker
控件。 这些名称与示例中的名称相同。另外,我将
BackgroundWorker
WorkerReportProgress
属性设置为
True
。未显示任何错误,项目已成功编译

问题 问题是-progressbar不移动。 然而,当手动单击时,它会移动<代码>progressBar1.PerformStep()

我错过了什么

密码 表格1.cs

使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用系统线程;
命名空间WindowsFormsApp2
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
私有void Form1_加载(对象发送方,System.EventArgs e)
{
//启动后台工作人员。
BackgroundWorker1.RunWorkerAsync();
}
私有void BackgroundWorker1\u DoWork(对象发送方,DoWorkEventArgs e)
{

对于(int i=1;i,在确保将事件处理程序附加到
ProgressChanged
DoWork
之后:

  • DoWork
    事件处理程序中删除
    progressBar1.PerformStep()
  • 然后在
    ProgressChanged
    事件处理程序中仅使用
    progressBar1.Value=e.ProgressPercentage;

  • 几年前,我用Progress条形码编写了一个简单的多线程。希望它能帮助您:

    #region Primenumbers
    private void btnPrimStart_Click(object sender, EventArgs e)
    {
        if (!bgwPrim.IsBusy)
        {
            //Prepare ProgressBar and Textbox
            int temp = (int)nudPrim.Value;
            pgbPrim.Maximum = temp;
            tbPrim.Text = "";
    
            //Start processing
            bgwPrim.RunWorkerAsync(temp);
        }
    }
    
    private void btnPrimCancel_Click(object sender, EventArgs e)
    {
        if (bgwPrim.IsBusy)
        {
            bgwPrim.CancelAsync();
        }
    }
    
    private void bgwPrim_DoWork(object sender, DoWorkEventArgs e)
    {
        int highestToCheck = (int)e.Argument;
        //Get a reference to the BackgroundWorker running this code
        //for Progress Updates and Cancelation checking
        BackgroundWorker thisWorker = (BackgroundWorker)sender;
    
        //Create the list that stores the results and is returned by DoWork
        List<int> Primes = new List<int>();
    
    
        //Check all uneven numbers between 1 and whatever the user choose as upper limit
        for(int PrimeCandidate=1; PrimeCandidate < highestToCheck; PrimeCandidate+=2)
        {
            //Report progress
            thisWorker.ReportProgress(PrimeCandidate);
            bool isNoPrime = false;
    
            //Check if the Cancelation was requested during the last loop
            if (thisWorker.CancellationPending)
            {
                //Tell the Backgroundworker you are canceling and exit the for-loop
                e.Cancel = true;
                break;
            }
    
            //Determin if this is a Prime Number
            for (int j = 3; j < PrimeCandidate && !isNoPrime; j += 2)
            {
                if (PrimeCandidate % j == 0)
                    isNoPrime = true;
            }
    
            if (!isNoPrime)
                Primes.Add(PrimeCandidate);
        }
    
        //Tell the progress bar you are finished
        thisWorker.ReportProgress(highestToCheck);
    
        //Save Return Value
        e.Result = Primes.ToArray();
    }
    
    private void bgwPrim_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        pgbPrim.Value = e.ProgressPercentage;
    }
    
    private void bgwPrim_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        pgbPrim.Value = pgbPrim.Maximum;
        this.Refresh();
    
        if (!e.Cancelled && e.Error == null)
        {
            //Show the Result
            int[] Primes = (int[])e.Result;
    
            StringBuilder sbOutput = new StringBuilder();
    
            foreach (int Prim in Primes)
            {
                sbOutput.Append(Prim.ToString() + Environment.NewLine);
            }
    
            tbPrim.Text = sbOutput.ToString();
        }
        else 
        {
            tbPrim.Text = "Operation canceled by user or Exception";
        }
    }
    #endregion
    
    #区域素数
    私有无效btnPrimStart\单击(对象发送者,事件参数e)
    {
    如果(!bgwPrim.IsBusy)
    {
    //准备进度条和文本框
    int temp=(int)nudPrim.Value;
    pgbPrim.最大值=温度;
    tbPrim.Text=“”;
    //开始处理
    bgwPrim.RunWorkerAsync(临时);
    }
    }
    私有无效btnprimmcancel\u单击(对象发送者,事件参数e)
    {
    如果(bgwPrim.IsBusy)
    {
    bgwPrim.CancelAsync();
    }
    }
    私有void bgwPrim_DoWork(对象发送方,DoWorkEventArgs e)
    {
    int highestToCheck=(int)e.参数;
    //获取运行此代码的BackgroundWorker的引用
    //用于进度更新和取消检查
    BackgroundWorker thisWorker=(BackgroundWorker)发件人;
    //创建存储结果并由DoWork返回的列表
    列表素数=新列表();
    //检查1和用户选择的任何上限之间的所有不均匀数
    对于(int PrimeCandidate=1;PrimeCandidate
    通常,当从Alterante线程编写UI元素时,您必须使用。BackgroundWorker很好,可以在创建它的线程上调用“ReportProgress”和“RunWorkerCompleted”事件(应该是GUI线程),因此您还不必处理多线程方面的问题

    捕获通常会逃避DoWork并被吞并的任何异常,并在已完成的事件Args中将它们公开给您,这也足够好了。吞并异常是多线程的一个大问题


    核心问题是,您的循环由于异常而中断。在内部调用
    progressBar1.PerformStep();
    DoWork事件必须抛出“CrossThreadException”。BackgroundWorker完成(由于异常)立即。当我只是初始值时,会触发RunWorker completed事件。

    我建议尝试在调用
    Dispatcher.CurrentDispatcher.Invoke()时包装
    progressBar1.PerformStep();
    )您不应该更新UI,在本例中是从工作线程内更新进度。这就是
    报告进度
    的目的。2)为什么您在
    工作
    进度更改
    中都执行
    执行步骤
    ?仅在后者中执行3)不要同时使用
    执行步骤
    进度Bar1.Value=xxx
    @Alex不正确。
    BackgroundWorker
    的要点在于它将在工作线程中执行的操作与UI的更新方式分开。更新是
    #region Primenumbers
    private void btnPrimStart_Click(object sender, EventArgs e)
    {
        if (!bgwPrim.IsBusy)
        {
            //Prepare ProgressBar and Textbox
            int temp = (int)nudPrim.Value;
            pgbPrim.Maximum = temp;
            tbPrim.Text = "";
    
            //Start processing
            bgwPrim.RunWorkerAsync(temp);
        }
    }
    
    private void btnPrimCancel_Click(object sender, EventArgs e)
    {
        if (bgwPrim.IsBusy)
        {
            bgwPrim.CancelAsync();
        }
    }
    
    private void bgwPrim_DoWork(object sender, DoWorkEventArgs e)
    {
        int highestToCheck = (int)e.Argument;
        //Get a reference to the BackgroundWorker running this code
        //for Progress Updates and Cancelation checking
        BackgroundWorker thisWorker = (BackgroundWorker)sender;
    
        //Create the list that stores the results and is returned by DoWork
        List<int> Primes = new List<int>();
    
    
        //Check all uneven numbers between 1 and whatever the user choose as upper limit
        for(int PrimeCandidate=1; PrimeCandidate < highestToCheck; PrimeCandidate+=2)
        {
            //Report progress
            thisWorker.ReportProgress(PrimeCandidate);
            bool isNoPrime = false;
    
            //Check if the Cancelation was requested during the last loop
            if (thisWorker.CancellationPending)
            {
                //Tell the Backgroundworker you are canceling and exit the for-loop
                e.Cancel = true;
                break;
            }
    
            //Determin if this is a Prime Number
            for (int j = 3; j < PrimeCandidate && !isNoPrime; j += 2)
            {
                if (PrimeCandidate % j == 0)
                    isNoPrime = true;
            }
    
            if (!isNoPrime)
                Primes.Add(PrimeCandidate);
        }
    
        //Tell the progress bar you are finished
        thisWorker.ReportProgress(highestToCheck);
    
        //Save Return Value
        e.Result = Primes.ToArray();
    }
    
    private void bgwPrim_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        pgbPrim.Value = e.ProgressPercentage;
    }
    
    private void bgwPrim_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        pgbPrim.Value = pgbPrim.Maximum;
        this.Refresh();
    
        if (!e.Cancelled && e.Error == null)
        {
            //Show the Result
            int[] Primes = (int[])e.Result;
    
            StringBuilder sbOutput = new StringBuilder();
    
            foreach (int Prim in Primes)
            {
                sbOutput.Append(Prim.ToString() + Environment.NewLine);
            }
    
            tbPrim.Text = sbOutput.ToString();
        }
        else 
        {
            tbPrim.Text = "Operation canceled by user or Exception";
        }
    }
    #endregion