Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# threading and polling

Tags:

c#

I have a tray icon that needs to display two icons:

  1. If there is network connectivity, display a green circle with a check mark
  2. If there isn't network connectivity, display a red circle with an X

So what I have is:

using System.Net.NetworkInformation;

bool isConnected = NetworkInterface.GetIsNetworkAvailable()

So I'm thinking of starting a new thread or using the background worker progress because the tray icon is a NotifyIcon which is a component so I can't use:

Form.Invoke(delegate, object[])

to update the icon property of the NotifyIcon class.

My big concern is the polling process: I could write some logic that does:

while (true) 
{
    System.Threading.Thread.Sleep(1000);
    isConnected = NetworkInterface.GetIsNetworkAvailable();
    if (isConnected)
        notifyIcon.Icon = "ConnectedIcon.ico";
    else
        notifyIcon.Icon = "DisconnectedIcon.ico";
}

but I've seen a couple of articles that tell me to stay away from Sleep(1000). I can't seem to find those articles since I didn't bookmark them. I'm just curious to know why that isn't a good idea for polling in a thread.

like image 351
coson Avatar asked Nov 29 '11 07:11

coson


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".

What kind of language is C?

C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system.


1 Answers

You can register an Event on NetworkChange so you are being notified when the status changes:

NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);

void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)  
{
    if (e.IsAvailable) {
        Console.WriteLine("Network Available");
    } else {
        Console.WriteLine("Network Unavailable");
    }
}
like image 165
oberfreak Avatar answered Sep 21 '22 06:09

oberfreak