C# Only One Thread Executes

c#, multithreading

Solution

You can use a lock object in combination with `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);
        }
    }
}

Only one thread at at time will be allowed into the `Monitor.TryEnter` block. If a thread arrives here while another thread is inside, then `Monitor.TryEnter` returns `false`.

Problem

I have a multithread application. I want only one thread to execute my function and other threads to pass it while my function executing. How can I do this? My method is something like: ``` 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); } } ```

Original source