我想检查我的函数在x秒内执行了多少次,比如3秒,我看到了一个类似但不完整的堆栈示例,填充我的prob。
实际上,我正在处理自动化用户界面,我的事件执行了很多次,所以我有一个解决方案,就是将对话的名称传递给我的函数,并且需要检查是否有相同的名称传递给功能,如果在接下来的3-4秒内执行的相同,如果是的话,我将返回我的事件处理程序,下面是我的代码到事件自动化UI。
Automation.AddAutomationEventHandler(
WindowPattern.WindowOpenedEvent,
AutomationElement.RootElement,
System.Windows.Automation.TreeScope.Subtree,
(sender, e) =>
{
string dialogueName = sd.Current.Name;
if (element.Current.LocalizedControlType == "Dialog")
{
starttimer(dialogueName );//how to get returned value there
}
}
});功能码
public static nameRecent;
public bool checkerfunctionOFname(string name )
{
if (nameRecent==name)
{
return;
}
}原因为什么我需要计时器3-4秒是假设用户打开一个保存作为对话,但关闭之后10 ec再次打开,所以这个匹配的前一个打开名称是静态的,但当他打开保存为对话时,同样重复它自己在3秒内,所以如果功能再次执行是3秒,它返回假等。
代码的解决方案,但是当函数返回false时,如何在事件处理程序中得到它,或者如何阻止它返回主函数。
public static string globalfucntiontime;
public static string globalfucntionname;
int _counter = 0;
Timer timer;
public void starttimer(string name){
_counter = 0;
timer = new Timer();
timer.Interval = 1000;
timer.Tick += (sender, args) =>
TimerEventProcessor(name); //how to get its returned value
globalfucntiontime = _counter.ToString();
timer.Start();
}
private bool TimerEventProcessor(string name)
{
globalfucntionname = name;
if (_counter <= 3 && name == globalfucntionname)
{
return false;
}
else if (name != globalfucntionname)
{
}
globalfucntiontime = _counter.ToString();
_counter += 1;
return true;
}发布于 2016-07-25 08:29:59
将名称和调用时间戳存储到字典中。现在你可以问字典,如果那个名字是在最后n秒钟内被调用的。
public class Foo
{
private readonly IDictionary<string,int> lastcalled = new Dictionary<string,int>();
public void RegisterCallOf( string name )
{
int now = Environment.TickCount;
if ( lastcalled.ContainsKey( name ) )
lastcalled[name] = now;
else
lastcalled.Add( name, now );
}
public bool WasCalledDuringLast( string name, int milliseconds )
{
int now = Environment.TickCount;
if ( lastcalled.ContainsKey( name ) )
return now - lastcalled[name] <= milliseconds;
return false;
}
}使用示例
// check if that "bar" was already called within the last 3000ms
if ( !foo.WasCalledDuringLast( "bar", 3000 ) )
{
// it was not, so now we register this call
foo.RegisterCallOf( "bar" );
// and now call that bar method
}更新
为了更容易地使用,可以用
public void ExecuteIfWasNotCalledDuringLast( string name, int milliseconds, Action action )
{
if ( !WasCalledDuringLast( name, milliseconds ) )
{
RegisterCallOf( name );
action();
}
}你要用这个方法
foo.ExecuteIfWasNotCalledDuringLast( "bar", 3000, barAction );https://stackoverflow.com/questions/38562428
复制相似问题