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);
}
}
You can use a lock object in combination with
Monitor.TryEnter.Only one thread at at time will be allowed into the
Monitor.TryEnterblock. If a thread arrives here while another thread is inside, thenMonitor.TryEnterreturnsfalse.