其實可以在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;
}
}
}
//不過這樣做,記時不是很準,你可以試試
用一個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;
}
}
}
//不過這樣做,記時不是很準,你可以試試
解决方案 »
- for循环嵌套IF,和IF里嵌套for循环 效率的比较
- 一些面试常见的算法
- 谁有C#版的反向连接的例子
- 请教一个页码显示问题
- 我的程序有警告,你高手指点.
- C#开发ActiveX控件问题求助,200分奉上!
- 需求简单算法实现以下功能,请高手指点
- 快速揭帖!!!!
- 未处理的“System.InvalidCastException”类型的异常出现在 system.windows.forms.dll 中。其他信息: 指定的转换无效。在线急等,解决了
- 500分征集DevExpress for .net 系列控件之(提供FPT者请进!)
- C#里怎样实现UTF-8编码和gb2312编码之间的转换
- 高分请教!
线程调度是由操作系统管理的,这个算法是对用户程序透明的,我们无法也没有必要知道操作系统是如何调度线程的,所以没有办法保证一个线程执行了5秒CPU事件我们只可能知道自从这个线程执行以来系统时钟走了5秒,而这5秒中,该线程可能被挂起和执行无数次。如果是一个网络程序,如果你使用而Receive方法,那么当网络有问题造成没有数据的话,这时这个方法会挂起本线程直到有数据为止,而在挂起阶段,CPU 并不会调度这个线程。
如果是一个关于网络编程的,可以使用队列来处理,考虑异步!
try
{
th.Abort();
}
catch (Exception)
{
//
}
根本都不行,还是报错误。
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);
}
}
}
}
怎么到现在才弄出来,笨死了!