I have a try-catch statement in reference to downloading a file. When the file is downloaded, I then enable one of my menu items then turn off a timer set to retry the download in one minute.
My problem is that for some reason my trafficManagementToolStripMenuItem.Enabled = true; line is activating the catch statement even though the menu item is being enabled. The file correctly downloads and when I comment out that line, it works perfectly. But every time I run it, I get the “error” message box and the timer is not disabled even though the menu item correctly enables after the download is complete.
Any ideas?
try
{
////downloads Data
string address = "http://website.file.txt";
string filename = "vsd.txt";
WebClient client = new WebClient();
client.DownloadFile(address, filename);
trafficManagementToolStripMenuItem.Enabled = true;
timer1.Enabled = false;
}
catch
{
timer1.Enabled = true;
MessageBox.Show("error", "test");
}
You don’t say what the exception is, but I’d guess that you’re running your download routine in a background thread, is that right? You can only access controls from the thread that created them: the main UI thread. Accessing a control such as a ToolStripMenuItem from a background thread will cause an exception.
If this is the case, use the Control.Invoke or Control.BeginInvoke method to run the
.Enabled = truecall on the ToolStripMenuItem’s thread. To do this, you’ll need a Control (unfortunately ToolStripMenuItem is only a Component). I’ll assume you can get a reference to the containing Form from somewhere. Now you can write this:This causes the
enableActionto run on the correct UI thread forform.