views:

256

answers:

4

I need to ensure that, once the execution hits a method, the control received by this method is not changed by another thread. Basically, I thought in something like this:

private void doSomeWork(Control control) {
    lock (control) {
        // do some stuff with the control...
    }
}

Is this a bad idea?

Edit:

Actually, what I'm trying to do, is to ensure that the control will not disposed by another thread while I execute some of the control's methods (which, by the way, will be executed via reflection).

+4  A: 

In a well behaving application, windows forms controls are already restricted to only one thread. If any thread tries to access a control created in a different thread, an exception will be thrown.

There is nothing wrong about your code, just know that right now it's mostly useless unless you are hacking your way through the protection (which is possible).

Usually, when you have data being created or manipulated in a working thread, the working thread will send an event to the UI thread to update the UI. In no way should a working thread updates the UI itself, it will automatically fail.

Coincoin
A: 

Actually Fernando, it's not a bad idea but it's not the correct way to look at locking. You need to closely read what the lock statement does in .Net:

http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx

i think that from your statement you expect the whole object to be locked, or somehow be made safe for threading, because the object iteself is used in a locked block of code. What actually happens is that block of code is locked and not allowed to be executed by two or more threads at the same time. If that block of code is the only place you're going to be operating on the control then you're ok, otherwise you'll need to do synch locks on the object itself.

Paul Sasik
A: 

Don't have a lot of experience working with threads, but, maybe I'll suggest you to start the Form Control in a new thread using an anonymous delegate:

t= new Thread(delegate() {
    MyMethodToInvokeTheWinFormControl();
   });

t.Start();
HJ42
A: 

It depends entirely on what you mean by "not changed".

If your meaning is "any other thread cannot change this control, at all, in any way", then that's not how lock works.

A lock in this sense is not like a regular lock on a door to a house. It's more like a small yellow post-it note that says "Locked". As long as other threads read the note and abide by what it says, it should be fine, but any other thread that doesn't care about the note at all will of course not be prevented from messing with your control.

In any case, what exactly are you trying to accomplish? You should never be messing with controls from other than the main thread so the problem shouldn't exist in the first place.

Instead you should be marshalling all work on the control onto the main thread through the use of the Invoke method on the control.

Lasse V. Karlsen