好的,我有一个模拟器,其中包含一些方法和一个计时器。我在这里启动计时器:
private void StartSimulation(object sender,EventArgs e)
{
while(execList.Count != 0)
{
Assign(MF,Mpre);
retCT = ChooseTransition(execList);
ttoexec = retCT[1];
this.time = retCT[0];
timer.Start();
// I need to stop execution of this method here untill timer stops ticking
ExecuteTransition(ttoexec);
execList.Remove(ttoexec);
}
}
定时器方法如下:
private void Timer_Tick(object sender,EventArgs e)
{
--time;
++k;
output.Add("t.u : " + k + " " + "M = [" + MF.GetRowVal() + "];");
if (time == 0)
{
timer.Stop();
}
}
变量 time 是 int 类型,保存时间需要计时的秒数(即 time * 定时器间隔时间的 1000 ms)。请注意,在 StartSimulation 方法中,我使用数组中的值设置时间。
更新
我正在使用System.Windows.Forms.Timer
我希望我的 StartSimulation()
停止执行,直到计时器停止(直到在 Timer_Tick
中执行 timer.Stop()
)输出是一个字符串列表,最后我将其写入一个txt文件中。
现在的问题是 StartSimulation()
的执行与计时器计时同时进行,因此输出列表只有 1 个元素(我在 开头插入的那个元素) StartSimulation()
代码,我没有将其粘贴到此处)。
所以我打开txt文件,写入内容,关闭它,计时器仍在运行。当调用timer.Start()方法时,StartSimulation
的执行应该停止
最佳答案
您可以检查“Enabled”属性。
根据official documentation , 通过将 Enabled
设置为 false
来停止引发 Elapsed
事件。
关于c# - 在 C# 中强制方法等待计时器停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52800446/