Can I add an attribute to a function to prevent reentry?

前端 未结 9 2327
梦谈多话
梦谈多话 2021-02-15 12:26

At the moment, I have some functions which look like this:

private bool inFunction1 = false;
public void function1()
{
    if (inFunction1) return;
    inFunctio         


        
9条回答
  •  盖世英雄少女心
    2021-02-15 12:55

    Instead of using a bool and setting it directly, try using a long and the Interlocked class:

    long m_InFunction=0;
    
    if(Interlocked.CompareExchange(ref m_InFunction,1,0)==0)
    {
      // We're not in the function
      try
      {
      }
      finally
      {
        m_InFunction=0;
      }
    }
    else
    {
      // We're already in the function
    }
    

    This will make the check thread safe.

提交回复
热议问题