Skip to main content
 首页 » 编程设计

c#之在特定时间内保持功能处于事件状态,如果条件为真之结束外观\功能

2024年02月13日13sxdcgaq8080

这有点乱,很抱歉,

我是 C# 的新手,所以我的问题可能很愚蠢,再次对此感到抱歉。

我想要完成的是这样的事情:

            private void RivalAlive() 
        // The Function Should be alive for 10min - if the condition is performed then the function need to die (quit) immediately, also if the 10min has passed without the condition beeing performed the function will die. 
        { 
            if (SmallHour == 5) // if condition is performed it need to execute the code in the condition and quit the function 
            //Run Another Function Here 
            //End the RivalAlive Function 
        { 
        } 
            //If the Condition is False - keep with the loop every 1 sec till 10min has passed 
        } 

非常感谢!

请您参考如下方法:

考虑到您只想在接下来的 10 分钟内轮询 SmallHour 的值,函数如下:

private void RivalAlive() 
{ 
    DateTime S = DateTime.Now; 
 
    while(DateTime.Now.Subtract(S).TotalSeconds < 600 && SmallHour !=5) 
         System.Threading.Thread.Sleep(1000); 
 
    if(SmallHour == 5) 
         EnterYourFunction(); 
} 

此函数将在接下来的 10 分钟内每隔一秒检查一次 SmallHour 的值。如果值为 5,它将退出。否则它会在 10 分钟后自动退出。