程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#線程資源同步方式總結(4)

C#線程資源同步方式總結(4)

編輯:關於C語言

輸出信息如下

可見,使用Monitor,我們能實現一種喚醒式的機制,相信在實際應用中有不少類似的場景。

5.使用System.Threading.Mutex(互斥體)類實現同步

在使用上,Mutex與上述的Monitor比較接近,不過Mutex不具備Wait,Pulse,PulseAll的功能,因此,我們不能使用Mutex實現類似的喚醒的功能,不過Mutex有一個比較大的特點,Mutex是跨進程的,因此我們可以在同一台機器甚至遠程的機器上的多個進程上使用同一個互斥體。

考慮如下的代碼,代碼通過獲取一個稱為ConfigFileMutex的互斥體,修改配置文件信息,寫入一條數據,我們同時開啟兩個相同的進程進行測試

using System;
using System.Collections.Generic;
using System.Text; using System.Threading;
using System.IO; using System.Diagnostics;
namespace MonitorApplication
{
class Program
{
static void Main(string[] args)
{
 Mutex configFileMutex = new Mutex(false, "configFileMutex");
Console.WriteLine("Wait for configFileMutex Process Id : " + Process.GetCurrentProcess().Id);
configFileMutex.WaitOne();
 Console.WriteLine("Enter configFileMutex Process Id : " + Process.GetCurrentProcess().Id);
System.Threading.Thread.Sleep(10000);
if (!File.Exists(@".config.txt"))
{
 FileStream stream = File.Create(@".config.txt");
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine("This is a Test!");
writer.Close();
stream.Close();
}
else
{
String[] lines = File.ReadAllLines(@".config.txt");
for (int i = 0; i < lines.Length; i++)
Console.WriteLine(lines[i]);
}
configFileMutex.ReleaseMutex();
configFileMutex.Close();
 }
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved