C# 同步工作站与SQL服务器的时间并设置为本机时间:
>需要采用TCP协议到网络服务器上获取时间
>在winform项目中,打开工具箱,找到timer控件
把timer控件拖动到winform窗体中,窗体下方会自动出现时间控件的实例,默认名称是timer1
右击timer1,在菜单中选择“属性”来打开属性窗口
在属性窗口中可以看到timer1的属性,其中红框中的属性是比较常用和重要的
Enabled属性表示timer是否可用,如果设置为true,则项目运行后,timer会自动启用;interval属性表示时间控件执行事件的时间间隔。要注意的是interval的单位是毫秒
为了展示timer的使用效果,可以在winform中拖入一个lable控件,默认生成lable1实例
在winfrom窗体上双击timer1进入后台代码timer1时间间隔事件。在箭头处书写代码,比如这里引用lable1控件来展示当前的时间
运行工程,可以看到窗体上的时间是按秒变化的在工具箱里有一个dateTimePick的控件是用来获取系统当前时间滴,将这个控件放到窗体中,可以看到电脑上的时间和那个winfrom窗体中datetimepick控件中显示的时间是一样的。
要它显示在textbox的文本框中:再在窗体中加一个textbox,一个button。双击button1
写代码
DateTime dt=dateTimePick1Value;
textBox1Text=dtToLongDateString()ToString();
运行后点击button1,时间就显示在textbox1中了第一种方法利用SystemDateTimeNow
[csharp] view plaincopy
static void SubTest()
{
DateTime beforDT = SystemDateTimeNow;
//耗时巨大的代码
DateTime afterDT = SystemDateTimeNow;
TimeSpan ts = afterDTSubtract(beforDT);
ConsoleWriteLine("DateTime总共花费{0}ms", tsTotalMilliseconds);
}
第二种用Stopwatch类(SystemDiagnostics)
[csharp] view plaincopy
static void SubTest()
{
Stopwatch sw = new Stopwatch();
swStart();
//耗时巨大的代码
swStop();
TimeSpan ts2 = swElapsed;
ConsoleWriteLine("Stopwatch总共花费{0}ms", ts2TotalMilliseconds);
}
第三种用API实现:
[csharp] view plaincopy
[SystemRuntimeInteropServicesDllImport("Kernel32dll")]
static extern bool QueryPerformanceCounter(ref long count);
[SystemRuntimeInteropServicesDllImport("Kernel32dll")]
static extern bool QueryPerformanceFrequency(ref long count);
static void SubTest()
{
long count = 0;
long count1 = 0;
long freq = 0;
double result = 0;
QueryPerformanceFrequency(ref freq);
QueryPerformanceCounter(ref count);
//耗时巨大的代码
QueryPerformanceCounter(ref count1);
count = count1 - count;
result = (double)(count) / (double)freq;
ConsoleWriteLine("QueryPerformanceCounter耗时: {0} 秒", result);
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)