如何建立一个超时函数
做一个超时函数
Dim Tim As Single
Dim State As New WaiteObject
State = sender
Tim = VB.DateAndTime.Timer
Do While Not blInput
Application.DoEvents()
If VB.DateAndTime.Timer - Tim > state.intTime Then
blInput = True
If blSend Then blSend = False
blErr = True
If State.OpexType <> E_操作事件.e状态查询KT Then
Dec_Msg(State.ID, State.OpexType, E_响应码.e超时)
End If
Exit Do
End If
If blStop Then Exit Sub '强制退出
Loop
这样做的话在等待过程中占用CPU时间,请教如何做不占用CPU时间,用线程也可以。请高手指教!
[解决办法]
循环里加一个thread.sleep(100)就可以降低CPU占用.
不过最好还是使用线程,可以保证界面不失去响应.
[解决办法]
dim th as threading.thread =new threading.thread(addressof 过程名)
th.start
过程里写你要执行都部分
[解决办法]
using System;
using System.Threading;
namespace ReadBinary
{
class Program
{
/// <summary>
/// 超时进程
/// </summary>
class TimeOutThread{
DelegateSetState _SetState;
int _TimeOut;
public TimeOutThread(int timeout, DelegateSetState setstate)
{
_TimeOut =timeout;
_SetState = setstate;
}
public void Start(){
Thread.Sleep(_TimeOut);
_SetState.Invoke(true);
Console.WriteLine( "超时进程结束 ");
}
}
/// <summary>
/// 监视进程
/// </summary>
class ListenerThread {
DelegateGetState _GetState;
int _Timer;
public ListenerThread(int timer,DelegateGetState getState) {
_Timer = timer;
_GetState = getState;
}
public void Start() {
bool state;
while (!( state = _GetState())) {
Console.WriteLine( "超时进程没有结束 ");
Thread.Sleep(_Timer);
}
Console.WriteLine( "监视进程结束 ");
}
}
delegate void DelegateSetState(bool state);
delegate bool DelegateGetState();
static bool _IsEnd=false;
static DelegateSetState setState=new DelegateSetState(SetState);
static DelegateGetState getState = new DelegateGetState(GetState);
/// <summary>
/// 主进程
/// </summary>
/// <param name= "args "> </param>
static void Main(string[] args)
{
TimeOutThread tot = new TimeOutThread(1000, setState);
ThreadStart ts = new ThreadStart(tot.Start);
Thread th = new Thread(ts);
th.Start();
ListenerThread lt = new ListenerThread(200, getState);
Thread listener = new Thread(new ThreadStart(lt.Start));
listener.Start ();
Console.WriteLine( "主进程结束 ");
Console.Read();
}
static void SetState(bool state) {
_IsEnd = state;
}
static bool GetState() {
return _IsEnd;
}
}
}