程序在執行中暫停一段時間?
在線程中,如果要暫停一定的時間,可以使用Thread的Sleep方法,讓線程暫停。在微軟新的win8API中,已經用Task來實現原來用線程實現的許多功能,同樣,Task也有Delay方法,讓程序暫停一定的時間。
以下程序利用System.Threading.Timer讓程序每隔間隔的時間執行回調方法:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace TimerApp{
class Program{
static void Main(string[] args){
Console.WriteLine("***** Working with Timer type *****/n");
// Create the delegate for the Timer type.
TimerCallback timeCB = new TimerCallback(PrintTime);
// Establish timer settings.
Timer t = new Timer(
timeCB, // The TimerCallback delegate type.
"Hello From Main", // Any info to pass into the called method (null for no info).
5000, // Amount of time to wait before Starting.
Timeout.Infinite); //一秒鐘調用一次 Interval of time between calls (in milliseconds).
Console.WriteLine("Hit key to terminate...");
Console.ReadLine();}
static void PrintTime(object state){
Console.WriteLine("Time is: {0}, Param is: {1}",
DateTime.Now.ToLongTimeString(), state.ToString());}
如果把時間間隔1000改成 Timeout.Infinite,這樣回調方法PrintTime只會在1秒之后調用一次。
除了Threading下有個Timer類之外,.net中還有另一個Timer,就是System.Timer名稱空間下的Timer。此Timer的用法和Threading下的Timer不太相同。
System.Timers.Timer t2 = new System.Timers.Timer(100);
t2.Elapsed += t2_Elapsed;
//t1.AutoReset = false;
t2.Enabled = true;}}
void t2_Elapsed(object sender, System.Timers.ElapsedEventArgs e){}
其中AutoReset屬性的含義是是否在每次時間間隔到了都觸發Elapsed事件還是只觸發一次(t1.AutoReset = false;)。
解決此類問題的一個小例子(實現在窗體上相隔指定時間顯示字幕)
//創建StopNtime類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace 程序運行暫停器{
class StopNtime{
public StopNtime(){
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//,跨線程調用控件必加上去 }
private int stopTime = 0;//暫停的時間
ThreadStart myStart;
Thread TheStop;
public readonly object MylockWord = new object();
public void stopWay(int stopTime){
this.stopTime = stopTime;
myStart = new ThreadStart(this .ToStop );
TheStop = new Thread(myStart );
TheStop.Start();
private void ToStop(){
lock (MyLockWord){
Thread.Sleep(this .stopTime );
Thread.CurrentThread.Abort();
//主窗體代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading ;
using System.Collections;
namespace 程序運行暫停器{
public partial class Form1 : Form{
public Form1(){
InitializeComponent();}
private void Form1_Load(object sender, EventArgs e){
label1.Text = "";
Thread f = new Thread(f1 );
f.Start();}
string MyWord = "問題:1+1=? ...\n答案是:2 ...";
private void f1(){
StopNtime mmm = new StopNtime();
foreach (char m in MyWord){
lock (mmm.MyLockWord ){
label1.Text += m.ToString();
mmm.stopWay(300);
//運行結果