于多线程的超时终止代码

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

}

posted on 2004-08-26 11:45 停留.Xp 阅读(920) 评论(0) 编辑 收藏

导航

<2004年8月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
2930311234

公告

昵称:停留.Xp
园龄:7年5个月
粉丝:0
关注:0

搜索

 
 

常用链接

随笔分类

随笔档案

相册

友情链接

最新评论

阅读排行榜

评论排行榜

推荐排行榜