Solved

Beginner BackgroundWorker Help Needed (C#)

Posted on 2008-10-22
8
2,857 Views
Last Modified: 2013-12-17
I need help understand the background worker, and what I am doing wrong in this example. I have a form with 2 radio buttons, and I want a background worker to perform a continious ping on a LAN IP address and if it loses connection I want the radio button to go to "disconnected" and if its successful I want the radio button to move to "successful". I want to do this in the background so you are free to use the rest of the form while remaining responsive. Here is my first attempt, but it fails to update either radiobutton and the form is not responsive at all:

namespace Background_Worker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        static BackgroundWorker worker = new BackgroundWorker();
        static string replyStatus;

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
           
            if (radioButton1.Checked == true)
            {
                radioButton2.Checked = false;
            }
        }

        private void pingIP(object sender, DoWorkEventArgs e)
        {
            Ping ping = new Ping();
            PingReply reply = ping.Send("192.168.1.200", 1000);
            if (reply.Status == IPStatus.Success)
            {
                replyStatus = "pass";
            }
            else
            {
                replyStatus = "fail";
            }
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked == true)
            {
                radioButton1.Checked = false;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            worker.DoWork += new DoWorkEventHandler(pingIP);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(complete);
        }

        private void complete(object sender, RunWorkerCompletedEventArgs e)
        {
            if (replyStatus == "pass")
            {
                radioButton1.Checked = true;
            }
            else
            {
                radioButton2.Checked = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            while (true)
            {
                try
                {
                    worker.RunWorkerAsync();
                }
                catch
                {
                }
            }

        }
    }
}
0
Comment
Question by:Pretzel_Jesus
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 6

Expert Comment

by:RishadanPort
ID: 22779122
Look like in your button1_Click(object sender, EventArgs e) function, you have an infinite loop that continues to run operations asynchronously.

when you have this statement:

this.backgroundWorker1.RunWorkerAsync();  <--

When the program has finished executing that statement, does not mean that the backgroundworker has finished, it just means made the call to start the operation in the background worker.


An example MSDN documentation shows that you should do it like this listed below.
private void dowloadButton_Click(object sender, EventArgs e)
{
    // Start the download operation in the background.
    this.backgroundWorker1.RunWorkerAsync();
 
    // Disable the button for the duration of the download.
    this.dowloadButton.Enabled = false;
 
    // Wait for the BackgroundWorker to finish the download.
    while (this.backgroundWorker1.IsBusy)
    {
        // Keep UI messages moving, so the form remains 
        // responsive during the asynchronous operation.
        Application.DoEvents();
    }
 
    // The download is done, so enable the button.
    this.dowloadButton.Enabled = true;
}

Open in new window

0
 
LVL 6

Expert Comment

by:RishadanPort
ID: 22779167
This while loop waits for the background worker to finish. Since you need to continuously send "pings" you will also need an outer while loop, like the one you have.

0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 22779239
Try this way out:
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private BackgroundWorker worker = new BackgroundWorker();
 
        private void Form1_Load(object sender, EventArgs e)
        {
            worker.DoWork += new DoWorkEventHandler(pingIP);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        }
 
        private void pingIP(object sender, DoWorkEventArgs e)
        {
            PingReply reply;
            Ping ping = new Ping();
            while (true)
            {
                reply = ping.Send("192.168.1.200", 1000);
                if (reply.Status == IPStatus.Success)
                {
                    worker.ReportProgress(0); // pass
                }
                else
                {
                    worker.ReportProgress(1); // fail
                }
                System.Threading.Thread.Sleep(250); // "throttle" thread w/ delay
            };
        }
 
        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            radioButton1.Checked = (e.ProgressPercentage == 0);
            radioButton2.Checked = (e.ProgressPercentage == 1);
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            if (!worker.IsBusy)
            {
                worker.RunWorkerAsync();
            }
        }
 
    }

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 22779273
* oops...there should not be a semi-colon ";" at the closing bracket of my while() block!

0
 

Author Comment

by:Pretzel_Jesus
ID: 22779292
Idle_Mind: I tried your code and it throws the following exception:

This BackgroundWorker states that it doesn't report progress. Modify WorkerReportsProgress to state that it does report progress.
0
 
LVL 6

Expert Comment

by:RishadanPort
ID: 22779320
change

worker.WorkerReportsProgress = true;
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 22779336
Right...sorry.

Add this line:

    worker.WorkerReportsProgress = true;
        private void Form1_Load(object sender, EventArgs e)
        {
            worker.WorkerReportsProgress = true;
            worker.DoWork += new DoWorkEventHandler(pingIP);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        }

Open in new window

0
 

Author Closing Comment

by:Pretzel_Jesus
ID: 31508846
Thanks a lot this is exactly what I needed! Its hard to understand this stuff from reading books... solutions like this make it so much easier to understand :). Thanks again.
0

Featured Post

[Webinar] Code, Load, and Grow

Managing multiple websites, servers, applications, and security on a daily basis? Join us for a webinar on May 25th to learn how to simplify administration and management of virtual hosts for IT admins, create a secure environment, and deploy code more effectively and frequently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ASP.NET data base connection 35 93
PowerShell:  foreach where object notmatch? 17 76
Datagridview column resizing 8 26
Easiest intro into .NET CORE? 2 32
Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question