我正在创建一组线程来访问 Web 服务并返回值。如果 threading.timer 中的超时计时器超过,我已将 threading.timer 添加到每个线程并尝试释放线程使用的资源。
这里我是怎么做到的。
class ThreadTest
{
System.Threading.Timer ThreadTimeoutTimer = null;
private void ThreadStartMain()
{
ParameterizedThreadStart start = new ParameterizedThreadStart(new ThreadTest().ReadData);
Thread t = new Thread(start);
t.Start();
}
public void ReadData(object stat)
{
int _timeOutTimer = 60000;
Thread currentThread = Thread.CurrentThread;
ThreadTimeoutTimer = new System.Threading.Timer(ReleaseThread, currentThread, _timeOutTimer, Timeout.Infinite);
webservcieclient webcl = new webservcieclient();
webcl.GetData();
ThreadTimeoutTimer = null;
UpdateDB();
}
private void ReleaseThread(object state)
{
Thread runningThread = (Thread)state;
if (runningThread.IsAlive)
{
runningThread.Abort();
}
}
}
所以为了检查它是如何工作的,我让 webservcieclient 超过了超时时间。然后计时器触发并中止线程。
但后来我看到的是 webservcieclient 有时在网络/http 异常之后返回,它已经执行并抛出另一个异常,说线程被中止。另外 UpdateDB() 已经运行了两次。它是如何运行的,因为线程已经中止。是因为在访问 Web 服务方法时启动了另一个线程吗?