> All,
>
[quoted text clipped - 11 lines]
> "lock(this);"
> shown in other examples.
Take a look at code in C# that locks data using something like ILDASM.
This code:
lock(this)
{
//some code
}
is implemented like this:
Monitor.Enter(this);
try
{
//some code
}
finally
{
Monitor.Exit(this);
}
lock() is just syntactic sugar, you can use Monitor in your own code.
> How is thread locking done with C++ in a
> Windows form app?
The only think I should warn you (but I guess you know anyway) is that
you should never use a blocking thread synchronization on the GUI
thread. The reason is that when the thread is blocked it will not be
able to update the UI and as a consequence you'll find that the UI will
freeze.
Richard

Signature
Fusion Tutorial: http://www.grimes.demon.co.uk/workshops/fusionWS.htm
Security Tutorial:
http://www.grimes.demon.co.uk/workshops/securityWS.htm
bill - 29 Dec 2005 18:58 GMT
Richard,
Coincidentally, after my posting and before your response arrived I was
reading your excellent book "Programming with Managed Extensions for MS
Visual C++ .NET". Actually I poke around in it from time to time
looking for various things. In any case, I found your example on page
240 of using the ReaderWriterLock() to be clear and to the point. I
will say that I needed to stick a "return true" into your Data() class
before it would compile.
All of that being said, I finally ended up with the following:
if (0 == Interlocked::Exchange(&usingResource, 1))
{
// do stuff
//Release the lock
Interlocked::Exchange( &usingResource, 0);
}
Thanks for your response,
Bill
David Browne - 29 Dec 2005 19:30 GMT
>> All,
>>
[quoted text clipped - 32 lines]
>
> lock() is just syntactic sugar, you can use Monitor in your own code.
Further, typically in C++ a wrapper object with a destructor is used to
manage resource lifetime. In C++/CLI an object with a destructor or a
Disposable object declared in automatic storage will be automatically
cleaned up as it leaves scope. This is similar to the using block of C#.
EG
#include "stdafx.h"
using namespace System;
ref class Lock
{
Object^ o;
~Lock()
{
System::Threading::Monitor::Exit(o);
Console::WriteLine("Monitor Exited.");
}
public:
Lock(Object^ objectToLock)
{
o = objectToLock;
System::Threading::Monitor::Enter(o);
Console::WriteLine("Monitor Entered.");
}
};
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
Object^ o = gcnew Object();
{
Lock lock(o);
Console::WriteLine("Automatic Lock is in scope");
}
Console::WriteLine("Automatic Lock is out of scope.");
Console::ReadKey();
return 0;
}
Outputs:
Hello World
Monitor Entered.
Automatic Lock is in scope
Monitor Exited.
Automatic Lock is out of scope.
David