Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使应用程序在计时器中等待而不使用thread.sleep_C# - Fatal编程技术网

C# 如何使应用程序在计时器中等待而不使用thread.sleep

C# 如何使应用程序在计时器中等待而不使用thread.sleep,c#,C#,我怎样才能在计时器内循环? 如果我把这些代码放进去如果, 它能用,但我不想睡觉 if (a==true) { no color codes System.Threading.Thread.Sleep(300); green color codes System.Threading.Thread.Sleep(300); } time = Function.Get_Server_Time(false); dServer_Time = time.Rows[0]["ServerDate"].ToDat

我怎样才能在计时器内循环? 如果我把这些代码放进去如果, 它能用,但我不想睡觉

if (a==true)
{
no color codes
System.Threading.Thread.Sleep(300);
green color codes
System.Threading.Thread.Sleep(300);
}
time = Function.Get_Server_Time(false);
dServer_Time = time.Rows[0]["ServerDate"].ToDateTime();
long msecs = 0;

if (dTimeDef!= null)
{
 msecs = (dServer_Time.Ticks - dTimeDef.Ticks) / 10000;
}

if (a==true)
{

 if (dTimeDef == null || msecs>500)
 {
 no color
 }
else
 {
 green color
 }
dTimeDef = dServer_Time;


}
但是我想不穿线睡觉

if (a==true)
{
no color codes
System.Threading.Thread.Sleep(300);
green color codes
System.Threading.Thread.Sleep(300);
}
time = Function.Get_Server_Time(false);
dServer_Time = time.Rows[0]["ServerDate"].ToDateTime();
long msecs = 0;

if (dTimeDef!= null)
{
 msecs = (dServer_Time.Ticks - dTimeDef.Ticks) / 10000;
}

if (a==true)
{

 if (dTimeDef == null || msecs>500)
 {
 no color
 }
else
 {
 green color
 }
dTimeDef = dServer_Time;


}

我怎样才能改进它。它不是那样工作的

您可以使用
等待任务。延迟(*毫秒时间*)
。应该可以帮到你。

基于你的伪代码,我认为你不需要延迟。您需要每300毫秒触发一个事件,并且希望通过在其中一个控件中交替颜色来处理该事件

最简单的方法是使用并将其间隔设置为300毫秒,如下所示:

private Timer myTimer; 

public void InitTimer()
{
    myTimer = new Timer();
    myTimer.Tick += new EventHandler(myTimer_Tick);
    myTimer.Interval = 300; // in miliseconds
    myTimer.Start();
}
另外,我建议你不要认为颜色是交替的。把颜色看作是时间的函数。示例:以下函数将返回0或1,每300毫秒交替一次:

(current milliseconds ÷ 300) mod 2
然后可以使用此函数的输出来确定当前颜色应该是什么。这将比每次读取当前颜色并决定如何处理它更有效率和一致性

因此,您的事件处理程序可能是:

private void myTimer_Tick(object sender, EventArgs e)
{
    var green = (((float)System.Environment.TickCount / 300) % 2) != 0;
    SetColor( green ? Color.Green : Color.Empty);
}

如果已经有计时器,则代码不必休眠或等待。当计时器滴答声发生时执行一些操作什么类型的UI?Windows窗体?是的,win窗体。区别在于
等待任务。延迟
不会阻止线程,而
线程。睡眠
会阻止线程