I have a project where I need to update a labels text from inside another classes method. It’s worth noting that this method is being called from a Background worker thread.
I have tried passing in the text to update as a UserState Obj in the Workers ReportProgress(); method and then updating the label when the workers progress changed event is fired off on the main form. This works, but obviously only updates the labels text when the progress changed event is raised.
I have code that’s loading/removing proxies constantly and I need a label to show this as it happens (as opposed to only updating when the bg workers progress changed event fires). Hopefully someone can help.
Thanks
Edit* Here’s some code to make the problem a little easier to understand: –
public string Request(string action)
{
if (string.IsNullOrWhiteSpace(action))
{
return "";
}
HttpWebRequest req;
string response = string.Empty;
while (response.Equals(string.Empty) && proxy != null)
{
try
{
req = (HttpWebRequest)WebRequest.Create(action);
req.Proxy = proxy;
response = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd();
}
catch (Exception ex)
{
RemoveProxy(proxy);
MessageBox.Show("Proxy Removed: " + proxy.Address.ToString());
proxy = GenNewProx();
MessageBox.Show("New proxy" + proxy.Address.ToString());
}
}
return response;
}
^^^ – Where i need to set the labels text, using Msgboxs at the moment but updating a label on the main form is obviously preferable
foreach (string url in URLs)
{
result.URL = url;
result.Shares = grabber.GetFacebookShares(url);
result.Tweets = grabber.GetTweetCount(url);
result.PlusOnes = grabber.GetPlusOnes(url);
bgWorker.ReportProgress((outputGridView.Rows.Count * 100) / importGridView.Rows.Count, result);
}
^^^ – Inside the bg workers do_work method on the main form.
2nd Edit*
I’m a bit new to events but could i not fire off a custom event say Proxy_Changed everytime i switch proxys and pass in a string argument with the new proxy/msg w.e and then subscribe to this event in the main form, then set the label on the main forms text = the string args when this event fires off? I’m probably talking jibberish tbh though :/
It sounds from your question and subsequent comments to other answers that you are running your code within a WinForms project, correct me if I am wrong? In a winform the main program thread is usually always static (static void Main()) therefore you must make your EventHandler static also to avoid null exceptions. I believe this will resolve your issue as it sounds like the rest of your code is correct?