现在的位置: 首页 > 综合 > 正文

于多线程的超时终止代码

2012年04月10日 ⁄ 综合 ⁄ 共 1690字 ⁄ 字号 评论关闭
using System;
using System.Threading;

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);
            }

        }

    }

}


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);
    }

}

抱歉!评论已关闭.