我需要知道如何在计时器上刷新文本我不希望它检测到何时发生变化
我也希望有能力给它写信。
Console.Clear();
string filepath = @"StrWorkPathChat.log";
List<string> lines = File.ReadAllLines(filepath).ToList();
foreach (string line in lines)
{
Console.WriteLine(line);
}
Console.Write("");
string chat;
chat = Console.ReadLine();
lines.Add(chat);
File.WriteAllLines(filepath, lines);
我也是c#新手,所以不要为我糟糕的代码生气。
.NET中有两种通用定时器:
System.Threading.Timer
此类使您能够以指定的时间间隔连续调用委托。还可以使用此类在指定的时间间隔内安排对委托的单个调用。委托在ThreadPool线程上执行。
的例子:
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
private static Timer timer;
static void Main(string[] args)
{
timer = new Timer(
callback: new TimerCallback(TimerTask),
state: /* your state object here */,
dueTime: 1000,
period: 2000);
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}: done.");
}
private static void TimerTask(object timerState)
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}: starting a new callback.");
//you can cast timerState to it's concrete type here
}
}
与system . timers . timer类
另一个可以在多线程环境中使用的定时器是System.Timers.Timer,默认情况下它会在ThreadPool线程上引发一个事件。
创建System.Timers.Timer对象时,可以指定引发Elapsed事件的时间间隔。使用Enabled属性指示计时器是否应引发Elapsed事件。如果您需要在指定的时间间隔过后仅引发一次Elapsed事件,请将AutoReset设置为false。AutoReset属性的默认值为true,这意味着在interval属性定义的时间间隔内定期引发一个Elapsed事件。
你可以从这里开始阅读:https://learn.microsoft.com/en-us/dotnet/standard/threading/timers