其實可以在Class t1中加入記時功能,
用一個bool變量來標示是否超時,public class t1
{
bool bTimeOut = false;
private int i = -1;
public t1(int n)
{
    i = n;    
}
private void Timer()
{
   System.Thread.Sleep(5000);//5秒記時;
   bTimeOut = true;
}
public void showMsg
{
    //首先啟動記時線程
    Thread t = new Thread(new ThreadStart(this.Timer))
     t.IsBackGround = true;
     t.Start();
    //再來循環
    while(!bTimeOut)//超時時bTimeOut = true;退出循環
          {
              //Do your things;
           }
}
}
//不過這樣做,記時不是很準,你可以試試

解决方案 »

  1.   

    使用线程的jion方法,该方法的功能就是等待线程一个规定的时间,如在等待的时间内线程返回了,则该方法立即返回,如果在规定的时间里线程没有完成,则也返回!
      

  2.   


    线程调度是由操作系统管理的,这个算法是对用户程序透明的,我们无法也没有必要知道操作系统是如何调度线程的,所以没有办法保证一个线程执行了5秒CPU事件我们只可能知道自从这个线程执行以来系统时钟走了5秒,而这5秒中,该线程可能被挂起和执行无数次。如果是一个网络程序,如果你使用而Receive方法,那么当网络有问题造成没有数据的话,这时这个方法会挂起本线程直到有数据为止,而在挂起阶段,CPU 并不会调度这个线程。
      

  3.   

    我们不能知道一个线程是否执行了5秒,但可以知道从此线程开始运行,系统时钟走了多少秒钟。所以你需要在线程中设置一个变量来探测它到底获得cpu事件,不过也不准确。
    如果是一个关于网络编程的,可以使用队列来处理,考虑异步!
      

  4.   

    Abort方法可以终止一个线程,可能会在线程中引发一个异常,捕获以后不作处理即可
      

  5.   

    Abort方法可以终止一个线程,但处理的时候做处理也过不去。
    try
    {
      th.Abort();
    }
    catch (Exception)
    {
      //
    }
    根本都不行,还是报错误。
      

  6.   

    最近才弄出来,贴出来给大家参考参考:
    using System;
    using System.Threading;class test
    {
    public static void Main()
    {
    for(int i = 0; i < 10; i++)
    {
    ThreadTest tt = new ThreadTest(i * 10);
    tt.onOver = new EventOverHandler(test.showMsg);
    tt.TimeOut = 1000;
    tt.ThreadRun();
    }
    } public static void showMsg(int xx)
    {
    Console.WriteLine("The End {0}.", xx);
    }
    }public delegate void EventOverHandler(int x);public class ThreadTimeOut
    {
    protected Thread threadObj;
    protected int timeOut; public Thread ThreadObj
    {
    set { threadObj = value; }
    get { return threadObj; }
    } public int TimeOut
    {
    set { timeOut = value; }
    get { return timeOut; }
    } public virtual void OnTimeOut()
    {
    if(ThreadObj != null)
    {
    if(!ThreadObj.Join(timeOut))
    {
    ThreadObj.Abort();
    }
    }
    }
    }public class ThreadTest : ThreadTimeOut
    {
    private int x; public ThreadTest(int x)
    {
    this.x = x;
    } public EventOverHandler onOver; public void ThreadRun()
    {
    ThreadObj = new Thread(new ThreadStart(ThreadFunction));
    Thread th = new Thread(new ThreadStart(OnTimeOut));
    ThreadObj.Start();
    th.Start();
    } public void ThreadFunction()
    {
    for (int i = 0; i < 10; i++)
    {
    Console.WriteLine(x);
    Thread.Sleep(500);
    ++x;
    }
    onOver(x);
    } public override void OnTimeOut()
    {
    if(ThreadObj != null)
    {
    if(!ThreadObj.Join(timeOut))
    {
    ThreadObj.Abort();
    onOver(x);
    }
    }
    }
    }
      

  7.   

    我不早就告诉你用jion方法了么!
    怎么到现在才弄出来,笨死了!