C# 如果停止执行,如何在同一输出屏幕中停止执行并获得一次结果?
在同一页中停止执行后,如何获取计数?例如,现在这条线一直重复,直到我停止为止。它显示启动进程时剩余的计数。但我需要在我停止排队后剩下的计数 有人请帮帮我 该计划是——C# 如果停止执行,如何在同一输出屏幕中停止执行并获得一次结果?,c#,.net,.net-4.0,C#,.net,.net 4.0,在同一页中停止执行后,如何获取计数?例如,现在这条线一直重复,直到我停止为止。它显示启动进程时剩余的计数。但我需要在我停止排队后剩下的计数 有人请帮帮我 该计划是—— namespace Time_Writer { class Program { static int count = 1; static double seconds; static int total = 10000; private static
namespace Time_Writer
{
class Program
{
static int count = 1;
static double seconds;
static int total = 10000;
private static System.Timers.Timer aTimer;
static void Main(string[] args)
{
ReadCountFromFile();
aTimer = new System.Timers.Timer();
aTimer.Elapsed +=new System.Timers.ElapsedEventHandler(aTimer_Elapsed);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine("Press Enter To Exit The Program\n");
Console.ReadLine();
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
}
private static void ReadCountFromFile()
{
try
{
if (File.Exists(".\\mynumber.dat"))
{
using (var file = File.Open(".\\mynumber.dat", FileMode.Open))
{
byte[] bytes = new byte[4];
file.Read(bytes, 0, 4);
count = BitConverter.ToInt32(bytes, 0);
total = total - count;
Console.WriteLine("Total count left is = {0}", total);
Console.WriteLine("Limit = 10000");
Console.WriteLine("Count = {0}", count);
Console.WriteLine("Count: {0} of 10000. {1} remaining", count, 10000 - count);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Problem reading file.");
}
}
static void CurrentDomain_ProcessExit(Object sender, EventArgs e)
{
using (var file = File.Open(".\\mynumber.dat", FileMode.OpenOrCreate))
{
var buffer = BitConverter.GetBytes(count);
file.Write(buffer, 0, buffer.Length);
}
}
private static void aTimer_Elapsed(object source, ElapsedEventArgs e)
{
Console.WriteLine("Name is Yap {0}", e.SignalTime);
seconds += 5;
count += 1;
if (count>10000 || seconds == 86400)
{
aTimer.Enabled = false;
Console.WriteLine("\n\nTimer is off at {0}\n\n", e.SignalTime.TimeOfDay.ToString());
}
}
}
}
修改最后三行代码,如下所示。应用程序应该是一个控制台应用程序
static void Main(string[] args)
{
ReadCountFromFile();
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new System.Timers.ElapsedEventHandler(aTimer_Elapsed);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine("Press Enter To Exit The Program\n");
//Modification starts from here
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
Console.ReadLine();
//Modification ends from here
}
参见此处Fredrik的回答:-这是一个完整的示例程序,在单独的线程上运行一个空消息泵,本质上,他使用消息泵在控制台应用程序处理事件之前捕获事件。有一些注释表明,您需要一种优雅地退出应用程序的方法,以便您可以使用另一个函数替换CurrentDomain_ProcessExit,该函数在打印结果后由inturn调用CurrentDomain_ProcessExit。另请参见EricLaw-MSFT-answer。HTHany最终解决方案的完整源代码?