我正在創建一組線程來訪問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服務方法時啓動了另一個線程?
你使用哪個框架類來調用web服務?它是'WebClient'嗎? – dcastro
是的。其Web服務客戶端。 – FatalError
您能向我們展示您實際執行Web請求的行嗎? – dcastro