我可以将属性添加到一个函数prevent再入? [英] Can I add an attribute to a function to prevent reentry?

查看:168
本文介绍了我可以将属性添加到一个函数prevent再入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一些功能,这是这样的:

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

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

    // do stuff which might cause function1 to get called
    ...

    inFunction1 = false;
}

我想能够声明他们是这样的:

I'd like to be able to declare them like this:

[NoReEntry]
public void function1()
{
    // do stuff which might cause function1 to get called
    ...
}

有没有我可以添加到一个函数prevent再入属性?如果没有,我怎么会去制作一个?我听说过AOP属性可以使用之前和之后函数调用来增加code;他们将是合适的?

Is there an attribute I can add to a function to prevent reentry? If not, how would I go about making one? I've heard about AOP attributes that can be used to add code before and after function calls; would they be suitable?

推荐答案

,请尝试使用一个漫长而Interlocked类:

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.

这篇关于我可以将属性添加到一个函数prevent再入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆