Ran into an interesting problem yesterday and it continues today. I'm tossing in a more useful network awareness method into the project simply because ...well, its kinda weak to have it only check when the app starts so I find this awesome event handler that does exactly what I want. It checks for a network connection of any kind (and ignores loopback) and by using System.Net.NetworkInformation, 1 line sets this up ...if you press tab and let vstudio write the rest of it ...
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
and it gives you the method "NetworkChange_NetworkAvailabilityChanged" -- a delegate method, which is fine, until you try to update stuff on a winform and you get this nasty "Cross-thread" error -- rude surprise. Ok, fine. I find a param I can set to disable this exception, but we're not about that -- we're going to do it right so off to ::shivers:: MSDN help. 2 hours pass and it shows me an example of a good threading call and a bad threading call, both of which are like saying "nuclear physics starts with this 3 mile long calculation" and its great, but I want something thats clear, less cluttered and to the point. Well, the accountant suggests I check out CLR via C# and brain up on threads, so I do. Since delegates is a good place to start, I pop open chapter 15 to better understand what all a delegate does and expects and within that chapter it refers me to chapter 23 which talks in great depth about async operations -- imagine that.
Ok, so now it makes sense why its complaining. The two threads are independent and for no real good reason should one ever be allowed to talk to the other. Think about an HR app that would allow this ...mmm scary eh? So I come across a few year old blog, the only one I find that answers my question just the way I like it -- short, sweet, to the point and with the least amount of code as possible -- and it all makes perfect sense.
The long and short of it? Within the method it creates, use System.Thread and do a This.Invoke(new WaitCallback(<methodName>), <methodArguments if any>); and within your <methodName> call up your usual control.text = "new stuff" ...with no cross thread complains. Here's the rest of the snippet.
private void NetworkChange_NetworkAvailabilityChanged(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
{
//To view the cross-threading error, uncomment the lines below and comment out this.invoke
//bool alive = NetworkInterface.GetIsNetworkAvailable();
//if (alive)
// Status.Text = "Connected";
//else Status.Text = "Disconnected";
this.Invoke(new WaitCallback(CheckNetwork), NetworkInterface.GetIsNetworkAvailable());
}
private void CheckNetwork(object NetworkNowAlive)
{
bool alive = (bool)NetworkNowAlive;
if (alive)
Status.Text = "Connected";
else Status.Text = "Disconnected";
}