public int ReadLengthAndCount()
{
byte[] buf = new byte[infoSize];
if (infoSize > m_MemSize) return 2;
if (!m_bInit) return 1;
Marshal.Copy(m_pwData, buf, 0, infoSize);
string s = Encoding.Unicode.GetString(buf).Trim('\0');
string[] parts = Regex.Split(s, @"\s+");
m_length = Convert.ToInt32(parts[0]);
m_count = Convert.ToInt32(parts[1]);
return 0;
}
public int WriteLengthAndCount(int length, int count)
{
semWriteLength.WaitOne();
try
{
if (infoSize > m_MemSize) return 2;
if (!m_bInit) return 1;
string s = length.ToString() + " " + count.ToString();
byte[] buf = Encoding.Unicode.GetBytes(s);
Marshal.Copy(buf, 0, m_pwData, buf.Length);
return 0;
}
finally { semWriteLength.Release(); }
}
Semaphore 保護寫入操作,避免多進程競態。Encoding.Unicode 確保跨進程字串一致性。Regex.Split 解析長度與計數,彈性應對格式變化。完整工程原始碼下載:CSDN。環境:WinXP SP3、VS2005、.NET 2.0。