Need help with multithreading and InvalidOperationException

I

Ian Toltz

I've got a form element (a wizard, actually) which is giving me
problems when I try to invoke some of its methods from one of the
methods of a filesystemwatcher. Basically the watcher sits there
waiting to see the file and then it's supposed to go to the next page
(wizard1.Next()).

I get an InvalidOperationException when I do this, though, and as near
as I can tell it's because the watcher creates a new thread and it's
trying to access the form object from a different thread. I don't know
how to fix this, though. Any ideas? I found this helpful page (http://
msdn2.microsoft.com/en-us/library/ms171728.aspx) which seems to be
exactly what I'm asking about, but I just can't figure it out. I've
tried to adapt it to my situation, but it's just over my head... In
particular, the whole backgroundwatcher thing isn't working. For
example, if I do "BackgroundWatcher bgw" and then on the very next
line something like "bgw=new BackgroundWatcher()" it tells me that the
variable bgw is unknown.

Is there any way to force a FileSystemWatcher to use the same thread
it's started in? I don't want or need the user to do anything until
it's done looking anyways.
 
J

Jon Skeet [C# MVP]

Ian Toltz said:
I've got a form element (a wizard, actually) which is giving me
problems when I try to invoke some of its methods from one of the
methods of a filesystemwatcher. Basically the watcher sits there
waiting to see the file and then it's supposed to go to the next page
(wizard1.Next()).

I get an InvalidOperationException when I do this, though, and as near
as I can tell it's because the watcher creates a new thread and it's
trying to access the form object from a different thread. I don't know
how to fix this, though. Any ideas?

See http://pobox.com/~skeet/csharp/threads/winforms.shtml

Basically, you need to use Control.Invoke/BeginInvoke.

Is there any way to force a FileSystemWatcher to use the same thread
it's started in?

You can set the SynchronizingObject property to be one of your
controls. That way I believe the calls should end up on the UI thread.
 
I

Ian Toltz

Seehttp://pobox.com/~skeet/csharp/threads/winforms.shtml

Basically, you need to use Control.Invoke/BeginInvoke.



You can set the SynchronizingObject property to be one of your
controls. That way I believe the calls should end up on the UI thread.

That helped a lot and I got it working. Man, that's some weird stuff.

Anyways, thanks a ton!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top