I am having a problem with a treeview where I try to add a subnode based upon the Node.Text Index (I have also tried this based upon the int index – to no avail). This works wonderfully when ran synchronously. However I run the exact same thing Async (backgroundWorker) it throws an unhandled ArgumentOutOfRange Exception. Another odd part is that I’ve attempted to catch this Exception in two different areas. see code:
using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
int x = 0;
foreach (string subkey_name in key.GetSubKeyNames())
{
using (RegistryKey subkey = key.OpenSubKey(subkey_name))
{
foreach (string a in (string[])subkey.GetValue("Users", ""))
{
User u = new User(a);
usrs.addUser(new User(a));
wgs.addUserToWorkgroup(subkey_name, a);
usrs.AddWorkGroupToUser(subkey_name, a);
int trycount = 0;
TryAgain:
try
{
//here is where the exception occurs
ExecuteSecure(() => treeView1.Nodes[subkey_name].Nodes.Add(a, a));
}
catch (ArgumentOutOfRangeException)//This does not catch it.
{
trycount++;
if (trycount < 100)
{
goto TryAgain; //b/c I cannot catch it this never happens...
}
}
}
}
x++;
//System.Threading.Thread.Sleep(2);
//As you can see I've tried to let the tread sleep to resolve this
//- it will get a little farther but still eventually bomb out.
}
}
Here is the ExecuteSecure code (https://stackoverflow.com/a/8021020/1387186)
private void ExecuteSecure(Action a)
{
o = new object();
try
{
if (InvokeRequired)
{
lock (o)
{
BeginInvoke(a);
}
}
else
a();
}
catch (Exception) //again **sigh** this does not catch the error
{ }
You have several problems.
Invokecause the UI and worker threads to ping-pong back and forth and as such your worker thread now became useless.Anyone who monitors my answers on here knows how I feel about these marshaling techniques (like
Invoke). It can be (and usually is) the worst method of updating the UI. In fact, it is so overused that it has gotten to the point where I think it can be considered a form of cargo cult programming.What you should do is have your worker thread publish the data required to update the
TreeViewinto a queue and then have your UI thread pull it out via aSystem.Windows.Forms.Timeron an interval that works best for you. Here is what it would look like.