Re: Threading UI components
Re: Threading UI components
http://hantou.blogspot.com/2009/04/c...perations.html
You can also search this Google and this forum for "Cross thread exception" to find more info.
Re: Threading UI components
Thanks, that helped a bit -- I ended up finding this, which really got me going in the right direction. I modified my ObservablePhotoCollection class to this:
Code:
private void Update()
{
this.Clear();
new Thread(new ParameterizedThreadStart(AddPhoto)).Start(_directory as object);
}
void AddPhoto(object data)
{
foreach (FileInfo f in ((DirectoryInfo)data).GetFiles("*.jpg"))
try
{
Add(new Photo(f.FullName));
}
catch
{
MessageBox.Show("Cannot load image: " + f.FullName);
}
}
Everything works dandy, but if I switch between directories before the thread finishes executing, it will clear the list box, but the (not finished yet) thread continues to populate it with images from the LAST directory.
So, I tried to declare the thread (instead of just new Thread()) so I could manipulate it later using Start() and Abort(), like this:
Code:
Thread AddPhotoThread = new Thread(new ParameterizedThreadStart(AddPhoto));
private void Update()
{
AddPhotoThread.Abort();
Clear();
AddPhotoThread.Start(_directory as object);
}
But I keep getting this error:
Code:
A field initializer cannot reference the non-static field, method, or property
So, my next question: How do I setup my thread to start/stop later?
Re: Threading UI components
OK, after a bit more work, I've got this to work:
Code:
Thread AddPhotoThread;
private void Update()
{
try
{
AddPhotoThread.Abort();
}
catch
{
}
Clear();
AddPhotoThread = new Thread(new ThreadStart(AddPhoto));
AddPhotoThread.Start();
}
It seems to work, but it'll tank if I take out the try... catch... statement (since, on first run, the thread hasn't been set). I tried doing:
Code:
if(AddPhotoThread.IsAlive)
{
AddPhotoThread.Abort();
}
but that didn't work either. Any suggestions?
Re: Threading UI components
It's not good to ABORT a thread, unless you have to. Just raise an event on the change event, and set a boolean in the loop. if threadRunning = True
Re: Threading UI components
Quote:
Originally Posted by
dglienna
It's not good to ABORT a thread, unless you have to. Just raise an event on the change event, and set a boolean in the loop. if threadRunning = True
*looks embarrassed* Yeah, I should have thought of that, shouldn't have I?
Haha, how obvious is it that I'm an Electrical Engineering student who hasn't taken a programming class since Freshman year?
Anyway, next question: if it's not a good idea to abort a thread, then how should I stop it? Can I send it a message to stop inserting images into the listbox if I switch directories? Looking at my code, what's the easiest way to implement that?
Thanks for the help!