Memory Mapped File Mutex Problem

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
<br/>

I have two programs that need to communicate with each other. One is a windows service (which runs constantly) and the other is a WCF web api that has a short TTL. I dont think types of programs here make any difference in what I am trying to
do.
<br/>

The first program is the windows service - Constantly running
<pre class="prettyprint Mutex mutex;
MemoryMappedFile mmf;
int m_iOffset = 0;
int m_iLength = 255;
byte[] m_byBuffer;
bool mutexCreated;


private void Form1_Load(object sender, EventArgs e)
{
mutex = new Mutex(true, "MMF_IPC", out mutexCreated);
mmf = MemoryMappedFile.CreateOrOpen("testapplication", m_iLength);
}


private void button1_Click(object sender, EventArgs e)
{
m_byBuffer = new byte[m_iLength];
m_byBuffer = ToBytes(textBox1.Text);
using (var accessor = mmf.CreateViewAccessor(m_iOffset, m_byBuffer.Length))
{
accessor.WriteArray<byte>(0, m_byBuffer, m_iOffset, m_byBuffer.Length);
}
mutex.ReleaseMutex();
}

private byte[] ToBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}[/code]
The second program is a wcf api - Incremental calls whenever the user needs
<br/>

<pre class="prettyprint int m_iOffset = 0;
int m_iLength = 255;

private void button1_Click(object sender, EventArgs e)
{
byte[] buffer = new byte[m_iLength];
using (var mmf = MemoryMappedFile.OpenExisting("testapplication"))
{
using (var accessor = mmf.CreateViewAccessor(m_iOffset, buffer.Length))
{
Mutex mutex = Mutex.OpenExisting("MMF_IPC");
mutex.WaitOne();
accessor.ReadArray<byte>(0, buffer, 0, buffer.Length);
}
}
string str = System.Text.Encoding.Default.GetString(buffer);
MessageBox.Show(str);
}[/code]
<br/>
They can communicate but its not reliable.
Sometimes the program hangs, sometimes i get "Object synchronization method was called from an unsynchronized block of code." on the mutex.ReleaseMutex();

What am I missing? (thanks in advance for your help!)
<br/>


View the full article
 

Similar threads

L
Replies
0
Views
160
LearningVisualC2005
L
E
Replies
0
Views
124
elfenliedtopfan55
E
W
Replies
0
Views
92
want 2 Learn
W
Back
Top