n单击按钮可获得n个输出.只需单击一次即可获得一个输出 [英] n clicks on a button gives n outputs. Required is only one output resulting from one click

查看:92
本文介绍了n单击按钮可获得n个输出.只需单击一次即可获得一个输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的..所以我不知道为什么会这样.我想我在Java中也遇到了类似的问题..但是我不明白这些东西.我正在使用C#,在其中我有一个listview,单击一个按钮时会用远程服务器更新状态进行更新.我已经为此工作的代码.但是当我再次单击相同的按钮时,输出显示两次.如果我再单击一次,输出将显示三次,等等! 例如: 第一次点击:

ok.. so i have no idea why this is happening.I saw a similar problem in Java i guess.. but i don't understand any of that stuff. I am working with C# where I have a listview which is updated with remote servers update status on clicking of a button. i have got the code working for this. but when i click on the same button again, the output is displayed twice. If i click on it one more time the output is displayed thrice and so on!! for example: on first click:

xxx     login to server failed
yyy     login to server failed

第二次点击:

xxx     login to server failed
xxx     login to server failed
yyy     login to server failed
yyy     login to server failed

我正在使用backgroundworker,并在其中使用了并行的foreach循环.我在这里放入了所有涉及的函数,以便在那里有所有信息. 这是我的代码:

I am using a backgroundworker, and a parallel foreach loop in it.I have put in all the involved functions here so that there's all the information there.. sorry if that's too much! Here's my code:

    private void button1_Click(object sender, EventArgs e)                        //get update button
    {
        GlobalVariables._count = 0;
        Status.statusProgress obj1 = new Status.statusProgress();
        if (getupdate_button.Text == "Stop")
        {
            backgroundWorker1.CancelAsync();
            getupdate_button.Enabled = false;
        }
        else
        {
            getupdate_button.Text = "Stop";
            listView1.Items.Clear();
            //do stuff
            backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
        }
        if (backgroundWorker1.IsBusy)
        {
            if (backgroundWorker1.CancellationPending != true)
            {
                MessageBox.Show("Please wait till the pervious operation is completed!");
            }
            else 
            {
                Complete_label.Text = "Cancelling...";
                Complete_label.Visible = true;
            }
        }
        else
        {
            backgroundWorker1.RunWorkerAsync(obj1);                                //calling background worker
        }
    }

工作:

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)                         //the boss-- the background worker
    {
        System.ComponentModel.BackgroundWorker worker;
        worker = (System.ComponentModel.BackgroundWorker)sender;
        Status obj1 = new Status();
        Status.statusProgress obj = new Status.statusProgress();

        if ((backgroundWorker1.CancellationPending == true))
        {
            e.Cancel = true;
        }
        else
        {
            obj1.Calculation(worker, e);
        }
        e.Result = obj;
    }

计算方法:

    public void Calculation(System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e)
    {
        Status.statusProgress obj = (Status.statusProgress)e.Argument;
        //stuff

            var file = File.ReadAllLines(obj.SourceFile);

            List<string> namelist = null;
            namelist = new List<string>(file);
            Parallel.ForEach(namelist, /*new ParallelOptions { MaxDegreeOfParallelism = 4 }, */line =>
            //foreach (string line in namelist)
            {
                var progress = new statusProgress();
                progress.TotalSysCount = obj.TotalSysCount;
                Status.statusProgress result = new Status.statusProgress();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    worker.ReportProgress(result.SysCount, result);
                }
                else
                {
                    //this.SystemName = line;//file.ReadLine();                        
                    progress.SystemName = line;
                    //result = progress;
                    result = OneSystem(line);
                    //work with result
        }
                count1 = Interlocked.Increment(ref count);
                //stuff
                worker.ReportProgress(count1, progress);
                Thread.Sleep(200);

             });

        }
    }

报告进度方法:

     private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    try
                {
                    var newItem = listView1.Items.Add("");
                    newItem.SubItems.Add(result.SystemName);
                    newItem.SubItems.Add(result.StatusString);
                    newItem.SubItems.Add(result.AvailableUpdatesCount.ToString());
                }
                catch (Exception ex)
                {}

            update_text(result);
            progressBar1.Maximum = 100;
            int perc = (int)((result.SysCount * 100) / result.TotalSysCount);
            progressBar1.Value = perc;
            Complete_label.Text = perc.ToString()+"%";
            if (progressBar1.Value == 100)
            {
                Complete_label.Text = "Complete!";
                getupdate_button.Enabled = false;
            }
    }

推荐答案

我想问题出在这里:

backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;

如果每次执行整个 click 时都添加了ProgressChanged事件处理程序,则每次单击后,您将增加事件处理的次数.

If whenever you do the whole click you add a ProgressChanged event handler, after each click you'll be increasing the number of times that the event is being handled.

最后,您应该在某些应用程序的初始化代码或类构造函数中添加事件处理程序,而不要在click事件处理程序中添加事件处理程序.也就是说,您将确保在每个应用程序生命周期中一次添加backgroundWorker1_ProgressChanged事件处理程序.

At the end of the day, you should add event handlers in some application's initialization code or in your class constructor instead of doing so in the click event handler. That is, you'll be sure that you're adding backgroundWorker1_ProgressChanged event handler once per application life-cycle.

这篇关于n单击按钮可获得n个输出.只需单击一次即可获得一个输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆