Re: Sharing objects between application instances using WCF
Originally Posted by Eri523
BTW, can't lines 3 to 6 of your code snippet be contracted to:
Code:
Mutex^ m = gcnew Mutex( true, "WcfShareTestServerLaunchedEvent", mutexWasCreated );
No. The explicit WaitOne() and ReleaseMutex() calls are needed to synchronize additional clients while the server is starting up.
Consider the following code where a 10 second sleep is used to simulate the server startup.
Code:
using namespace System;
using namespace System::Threading;
using namespace System::Diagnostics;
int main(array<System::String ^> ^args)
{
bool mutexWasCreated;
Console::WriteLine( System::String::Format( L"Starting client: {0}", DateTime::Now ) );
Mutex^ m = gcnew Mutex( false, "WcfShareTestServerLaunchedEvent", mutexWasCreated );
// Block other processes until startup has completed
m->WaitOne( );
// Start up the server
if( mutexWasCreated )
{
Console::WriteLine( System::String::Format( L"Starting server - pid: {0}", Process::GetCurrentProcess( )->Id ) );
// Simulate startup up of WCF server (pause 10 seconds)
Thread::Sleep( 10000 );
}
// Allow access to other processes after startup has finished
m->ReleaseMutex( );
Console::WriteLine( System::String::Format( L"Using server - pid: {0}", Process::GetCurrentProcess( )->Id ) );
Console::WriteLine( System::String::Format( L"Client has access: {0}", DateTime::Now ) );
Console::ReadLine( );
return 0;
}
In the Visual Studio IDE, open multiple instances by clicking "Debug\Start without debugging" (or Ctrl+F5).
Notice the timings of "Client has access". You'll see that clients other than the first instance have to wait 10 seconds before getting access.
If you set the change the TakeOwnership to true during the mutex creation and remove the calls to WaitOne and ReleaseMutex, you'll see the "Client has access" appear immediately, which proves the clients aren't waiting for the server startup.
* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.