2014-07-19 20 views
0

我正在创建一组线程来访问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服务方法时启动了另一个线程?

+0

你使用哪个框架类来调用web服务?它是'WebClient'吗? – dcastro

+0

是的。其Web服务客户端。 – FatalError

+0

您能向我们展示您实际执行Web请求的行吗? – dcastro

回答

0

你得到了ThreadAbortException,因为这就是Thread.Abort所做的。但更重要的是,不要使用Thread.Abort

请参见:What's wrong with using Thread.Abort()

如果你希望能够取消线程,你应该使用更高级别的结构,像TPL的任务和CancellationToken。 下面是一个简短的例子:

public void Main() 
{ 
    //create a token that will be automatically cancelled after 60000 seconds 
    var cts = new CancellationTokenSource(60000); 

    Task task = Task.Run(() => ReadData(cts.Token)); 
} 

private void ReadData(CancellationToken token) 
{ 
    while (! token.IsCancellationRequested) 
    { 
     //do something 
    } 
} 
+0

但它是如何发生的。因为线程已经中止。这是网络例外,因为它在120秒后才会出现。所以我的问题是,如果线程已经中止它如何运行两次。 updateDB()调用两次。 – FatalError

+0

@FatalError它运行两次的事实必须由代码的其他部分来解释,而不是在问题中显示。您应该发布[最小,完整和可验证示例](http://stackoverflow.com/help/mcve) – dcastro

相关问题