Question BackgroundWorker. How do I display the current process by navigating through the Tree

csharBeginer

New member
Joined
Sep 1, 2018
Messages
3
Programming Experience
Beginner
Scenario_1.
1. The user. Presses the "Start" button;
2. The program. Creates an instance of the user element "ucBackgroundWorker" in "flowLayoutPanel1";
3. The program. Creates a node in the "treeView1";

"Scenario_1" can be repeated an unlimited number of times.

Scenario_2.
There are: - Several processes are started in "flowLayoutPanel1";
- in "treeView1" there is a tree of processes;

Scenario:
1. The user. Moves the cursor to "treeView1";
2. The program. In "flowLayoutPanel2" it displays the process (instance
"ucBackgroundWorker" ") of the node on which the cursor is located;


I tried to implement this scenario (Scenario_1 + Scenario_2) as I understand it. I thought that the user element instances can be assigned indexes, and then, depending on the index, display in "flowLayoutPanel2".
For the test, the button of this script made a button "btShowTheProces"
But the project does not work.
When debugging, I get an error.

Form3.cs

flowLayoutPanel1.Controls.Add(ucBgWorker [i_ucBWrk]);

Error "The object reference does not point to an instance of the object."
ucBgWorker = null;


Questions
1. How to fix the error?
2. Do I solve my problem correctly?
3. What are the other ways to accomplish this scenario?


Form3.cs
C#:
namespace rsh
{
    public partial class Form3 : Form
    {
        // ucBackgroundWorker[] ucBgWorker = null;
        
        int i_ucBWrk=0;
        private ucBackgroundWorker[] ucBgWorker;


        int procNumb;


        public Form3()
        {
            InitializeComponent();
        }


        // ????? ?????? ???? ??????
        void treeView1_AfterSelect(object sender, TreeViewCancelEventArgs e)
        {


        }


        private void btnStart_Click(object sender, EventArgs e)
        {
            i_ucBWrk++;


            ucBgWorker[i_ucBWrk] = new ucBackgroundWorker();


            // ucBgWorker[i_ucBWrk].Done += new Action<string, EventArgs>(Worker_Done);
            // ucBgWorker[i_ucBWrk].Cancel += new Action<string, EventArgs>(Worker_Cancel);


            flowLayoutPanel1.Controls.Add(ucBgWorker[i_ucBWrk]);


            ucBgWorker[i_ucBWrk].Run(1);            
            // ucBgWorker.Run(Convert.ToInt32(textBox1.Text));
        }


        void Worker_Done(string arg, EventArgs evtarg)
        {
            label1.Text = arg + " Done One";
            //System.Threading.Thread.Sleep(1000);
        }


        void Worker_Cancel(string arg, EventArgs evtarg)
        {
            label1.Text = arg + " Cancel Click";
            //System.Threading.Thread.Sleep(1000);
        }




        //  show the process
        private void btShowTheProces_Click(object sender, EventArgs e)
        {
            procNumb = Convert.ToInt32(numericUpDown1.Value);


            flowLayoutPanel2.Controls.Clear();
            flowLayoutPanel2.Controls.Add(ucBgWorker[procNumb]);
        }
    }
}


ucBackgroundWorker.cs

C#:
namespace rsh
{
    public partial class ucBackgroundWorker : UserControl
    {
        BackgroundWorker bgWorker = null;
        public event Action<string, EventArgs> Done;
        public event Action<string, EventArgs> Cancel;


        private static bool m_continue = true;


        // ?????????? ???? ??? ????? ????????? ??????? ? ???, ??? ????????? ???????. ???? ????? ?? ???????????.
        // https://msdn.microsoft.com/ru-ru/library/system.threading.manualresetevent(v=vs.110).aspx
        private ManualResetEvent _resetEvent = new ManualResetEvent(false);
        //Semaphore sWaiter = new Semaphore(0, 1);




        public ucBackgroundWorker()
        {
            InitializeComponent();


            bgWorker = new BackgroundWorker();


            bgWorker.WorkerSupportsCancellation = true;
            bgWorker.WorkerReportsProgress = true;


            bgWorker.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            bgWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        }


        public void Run(int counter)
        {
            if (!bgWorker.IsBusy)
            {
                bgWorker.RunWorkerAsync(counter);
            }
            _resetEvent.Set();
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int input = int.Parse(e.Argument.ToString());


            this.BeginInvoke((MethodInvoker)delegate
            {
                lblStatus.Text = "Running";
            });


            for (int i = 1; i <= input; i++)
            {
                _resetEvent.WaitOne();
                Thread.Sleep(1000);
                (sender as BackgroundWorker).ReportProgress(i*1); // ???
                // (sender as BackgroundWorker).ReportProgress(i * 10);
                if ((sender as BackgroundWorker).CancellationPending)
                {
                    this.BeginInvoke((MethodInvoker)delegate
                    {
                        lblStatus.Text = "Cancel";
                    });


                    e.Cancel = true;
                    return;
                }
            }
            Thread.Sleep(1000);
        }




        // This event handler deals with the results of the 
        // background operation.
        // ???? ?????????? ??????? ????? ???? ? ????????????
        // ??????? ????????.
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // First, handle the case where an exception was thrown. 
            // ??????? ???????????? ??????, ????? ???? ??????? ??????????.
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                if (Cancel != null)
                    Cancel(this.Name, EventArgs.Empty);
            }
            else
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    lblStatus.Text = "Done";
                });


                if (Done != null)
                    Done(this.Name, EventArgs.Empty);
            }
            _resetEvent.Reset();
        }


        // This event handler updates the progress bar. 
        // ???? ?????????? ??????? ????????? ????????? ??????????.
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pBar.Refresh();
            pBar.Value = e.ProgressPercentage;
        }






        // *** *** *** ***
        // *** ??????  ***
        // *** *** *** ***
        
        // Cancel
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (bgWorker.IsBusy)
            {
                bgWorker.CancelAsync();
            }
        }


        // Pause
        private void btnPause_Click(object sender, EventArgs e)
        {
            if (bgWorker.IsBusy)
            {
                if (btnPause.Text.ToUpper() == "PAUSE")
                {
                    btnPause.Text = "Resume";
                    m_continue = false;
                    _resetEvent.Reset();
                }
                else 
                if (btnPause.Text.ToUpper() == "RESUME")
                {


                    btnPause.Text = "Pause";
                    m_continue = true;
                    _resetEvent.Set();


                }
            }
        }




    }
}


 

Attachments

  • 2018-09-04_18-03-05.png
    2018-09-04_18-03-05.png
    12.1 KB · Views: 108
  • 01_pr.zip
    15.9 KB · Views: 61
Last edited by a moderator:
Before having even read your post, I'm going to say one thing upfront. That is way too much code to be posting. You should be making every effort to narrow down the issue and post only the relevant code. If necessary, you should create a new test project and add to that only what is required to reproduce the issue. That way, we don't have to waste our time wading through the irrelevant stuff. I'll take a look at your issue when I get the chance but I don't have time to go through all that right now.
 
Back
Top Bottom