Re: Intra-thread lock by cj_junktrap
cj_junktrap
Sun Jul 30 05:37:50 CDT 2006
Markus Stoeger wrote:
> cj_junktrap@mail.com wrote:
> > Hi
> >
> > Is there something like an intra-thread lock? I'm trying to prevent
> > re-entrant code, and the lock statement will only prevent one thread
> > from entering the critical section while another thread is in it -
> > since my code is triggered by a gui event, it's not impossible that it
> > could be called twice from the same thread. I could simulate a lock by
> > having a private variable "busy" and setting that to true when I start
> > processing, false when I stop, and check it before I begin processing -
> > but then either I have to throw an exception if I'm already busy
> > processing (which I'd prefer not to do), or I'd have to use a polling
> > wait loop to simulate a blocking call - which seems ugly.
> >
> > Any ideas of a better way to do this?
>
>
> I'm not 100% sure if I fully understand what you mean. While GUI event
> is being processed, you can be sure that it will _not_ be fired a second
> time because the windows message loop is blocked until your processing
> is done (unless you are calling something like Application.DoEvents in
> your processing code, which I hope you don't anyway ;-).
>
> Anyway, you cannot have the current thread wait until the current thread
> is done processing something else. That would always result in a dead lock.
>
> The method with the "busy" variable would work. If busy is already true
> -> handle it! Either by throwing an exception or by enqueuing the new
> work item somewhere for later processing.
>
> hth,
> Max
Well, I am using DoEvents, as I mentioned in the other thread, but even
without that it could still be called twice. Picture this: I have a
form, with two buttons. In my form constructor, or somewhere, I create
an instance of my object. Each button calls myObject.DoSomething(),
which, say, displays another form using form.Show(). When this other
form is closed, it raises an event or calls a delegate. Now the user
clicks on button 1, but doesn't close the form yet; then clicks on
button 2. My DoSomething() method will then be called again.
Basically, my problem is that I have an app with potentially many
forms; one of them will trigger the opening of a 2nd form. I want the
user to still be able to use the other forms, so I can't open this 2nd
form using ShowDialog, since it will be modal with respect to the
entire app. If I could make it modal only with respect to its parent
form, that would solve all my problems.