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 服务方法时启动了另一个线程吗?

4

1 回答 1

0

你得到一个ThreadAbortException,因为那是什么Thread.Abort。但更重要的是,不要使用Thread.Abort

请参阅:使用 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
    }
}
于 2014-07-19T14:57:09.560 回答