2012-05-20 58 views
0

我有一個控制檯應用程序,它將由不同的批處理文件設置windows任務計劃程序啓動。我想對這些命令進行排隊,或者在我的應用程序中設置某種鎖定機制,以使所有命令都在隊列中等待,這樣一次只能運行一個命令。我正在考慮做某種文件鎖定,但是我不能讓自己的腦袋纏繞在排隊命令的工作方式上。我只需要某種方向。爲控制檯應用程序創建鎖定

希望得到任何幫助。

感謝

回答

2

對於進程間同步,您可以使用表示命名系統互斥體的Mutex實例。

// Generate your own random GUID for the mutex name. 
string mutexName = "afa7ab33-3817-48a4-aecb-005d9db945d4"; 

using (Mutex m = new Mutex(false, mutexName)) 
{ 
    // Block until the mutex is acquired. 
    // Only a single thread/process may acquire the mutex at any time. 
    m.WaitOne(); 

    try 
    { 
     // Perform processing here. 
    } 
    finally 
    { 
     // Release the mutex so that other threads/processes may proceed. 
     m.ReleaseMutex(); 
    } 
} 
0

查找Semaphore對象。

_resultLock = new Semaphore(1, 1, "GlobalSemaphoreName"); 
if (!_resultLock.WaitOne(1000, false)) 
{ 
    // timeout expired 
} 
else 
{ 
    // lock is acquired, you can do your stuff 
} 

您可以隨時把你的超時時間是無限的,但實際獲得控制權,不時程序流程,並能夠正常中止。

相關問題