2012-05-25 111 views
5

我有一個多線程應用程序。我只想要一個線程來執行我的函數和其他線程來傳遞它,而我的函數正在執行。我怎樣才能做到這一點?C#只有一個線程執行

我的方法是這樣的:

public void setOutput(int value) 
    { 
     try 
     { 
      GPOs gpos = reader.Config.GPO; 
      gpos[1].PortState = GPOs.GPO_PORT_STATE.TRUE; 
      gpos[2].PortState = GPOs.GPO_PORT_STATE.TRUE; 
      Thread.Sleep(WAIT); 
      gpos[1].PortState = GPOs.GPO_PORT_STATE.FALSE; 
      gpos[2].PortState = GPOs.GPO_PORT_STATE.FALSE; 
     } 
     catch (Exception ex) 
     { 
      logger.Error("An Exception occure while setting GPO to " + value + " " + ex.Message); 
     } 
    } 

回答

10

您可以組合使用的鎖定對象與Monitor.TryEnter

private Object outputLock = new Object(); 

public void setOutput(int value) 
{ 
    if Monitor.TryEnter(outputLock) 
    { 
     try 
     { 
      .... your code in here 
     } 
     finally 
     { 
      Monitor.Exit(outputLock); 
     } 
    } 
} 

只有一個線程在時間將被允許進入Monitor.TryEnter塊。如果一個線程在另一個線程在裏面時到達,那麼Monitor.TryEnter返回false

+3

其他線程不會在鎖上排隊嗎?這似乎不是OP要求的內容 –

+0

@MatthewEvans是的,我誤解了*通過*的含義。我認爲編輯處理正確。 –

1

您可以使用Mutex

using System; 
using System.Threading; 

class Test 
{ 
    // Create a new Mutex. The creating thread does not own the 
    // Mutex. 
    private static Mutex mut = new Mutex(); 
    private const int numIterations = 1; 
    private const int numThreads = 3; 

    static void Main() 
    { 
     // Create the threads that will use the protected resource. 
     for(int i = 0; i < numThreads; i++) 
     { 
      Thread myThread = new Thread(new ThreadStart(MyThreadProc)); 
      myThread.Name = String.Format("Thread{0}", i + 1); 
      myThread.Start(); 
     } 

     // The main thread exits, but the application continues to 
     // run until all foreground threads have exited. 
    } 

    private static void MyThreadProc() 
    { 
     for(int i = 0; i < numIterations; i++) 
     { 
      UseResource(); 
     } 
    } 

    // This method represents a resource that must be synchronized 
    // so that only one thread at a time can enter. 
    private static void UseResource() 
    { 
     // Wait until it is safe to enter. 
     mut.WaitOne(); 

     Console.WriteLine("{0} has entered the protected area", 
      Thread.CurrentThread.Name); 

     // Place code to access non-reentrant resources here. 

     // Simulate some work. 
     Thread.Sleep(500); 

     Console.WriteLine("{0} is leaving the protected area\r\n", 
      Thread.CurrentThread.Name); 

     // Release the Mutex. 
     mut.ReleaseMutex(); 
    } 
} 
0

你可以給一個名稱,你的線程和方法

+0

而你如何同步呢? –

0

這個怎麼樣解決檢查名稱:

private AutoResetEvent are = new AutoResetEvent(); 

public void setOutput(int value) 
{ 
    // Do not wait (block) == wait 0ms 
    if(are.WaitOne(0)) 
    { 
     try 
     { 
      // Put your code here 
     } 
     finally 
     { 
      are.Set() 
     } 
    } 
} 

這似乎是比鎖定對象更容易(更便宜),但可能不太清楚。