gpt4 book ai didi

c# - 当计时器从 c# 控制台应用程序中的其他类停止时如何返回到 main

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:34 24 4
gpt4 key购买 nike

我有一个像下面这样的计时器类

public class helper
{
Timer timer = new Timer();
private int counter = 0;
private int returnCode = 0;


public int Process()
{
SetTimer();
Console.WriteLine("The application started ");
return counter;

}

public void SetTimer()
{
int optionalWay = 0;
// Create a timer with a two second interval.
timer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
timer.Elapsed += (sender, e) => OnTimedEvent(sender, e, optionalWay);

timer.AutoReset = true;
timer.Enabled = true;

}

private void OnTimedEvent(Object source, ElapsedEventArgs e, int optionalWay)
{
counter++;
Console.WriteLine("Timer is ticking");

if (counter == 10)
{
timer.Stop();
timer.Dispose();
returnCode = returnCode + 1;
}
}
}

下面是我的主要功能

public static void Main()
{
helper helper = new helper();
int code = helper.Process();
Console.WriteLine("Main " + code.ToString());
Console.ReadLine();
}

我想做的是在我的计时器停止时返回主线程,而不是在那之前

,我的计时器类运行良好,主要打印如下

所以main应该等到定时器的结果为1,然后结束进程

最佳答案

代码正常运行。 helper.Process()里面什么都没有可以等待或阻止执行的函数,因此该函数立即返回到 mainOnTimedEvent 之前甚至被执行。

解决方法可以通过在 helper 中实现一个事件来完成类并在计时器完成其工作后引发该事件。和 main可以收听该事件并采取相应行动。

public class helper
{
Timer timer = new Timer();
private int counter = 0;
private int returnCode = 0;

public event EventHandler<int> Done;
...

private void OnTimedEvent(Object source, ElapsedEventArgs e, int optionalWay)
{
counter++;
Console.WriteLine("Timer is ticking");

if (counter == 10)
{
timer.Stop();
timer.Dispose();
returnCode = returnCode + 1;

if (Done != null)
{
Done.Invoke(this, returnCode);
}
}
}
}

并且在 Program.cs

static void Main(string[] args)
{
helper helper = new helper();
helper.Done += helper_Done;
helper.Process();
Console.ReadLine();
}

static void helper_Done(object sender, int e)
{
Console.WriteLine("Main " + e.ToString());
}

更新

Timer 类使用来自 ThreadPool 的新线程来执行 Elapsed事件处理程序。所以它不能返回到 Main它在不同的线程上运行。简而言之:您尝试做的事情无法通过计时器实现。

这是另一个使用 Thread.Sleep() 的解决方案这将满足您的要求,但请记住使用 Thread.Sleep()像这样不推荐

public class helper
{
private int counter = 0;
private int returnCode = 0;

public int Process()
{
Console.WriteLine("The application started ");
StartTimer(2000);
return returnCode;
}

private void StartTimer(int ms)
{
while (counter++ < 10)
{
System.Threading.Thread.Sleep(ms);
Console.WriteLine("Timer is ticking");
}
returnCode = returnCode + 1;
}
}

class Program
{
static void Main(string[] args)
{
helper helper = new helper();
int code = helper.Process();
Console.WriteLine("Main " + code.ToString());
Console.ReadLine();
}
}

同样,这不是使用 Thread.Sleep 的好习惯延迟执行和 Thread.SleepTimer.Elapsed 相比不太准确.尝试更改应用程序的设计并使用事件回调函数

关于c# - 当计时器从 c# 控制台应用程序中的其他类停止时如何返回到 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48889113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com