你如何处理,有一个电话挂起一个线程? [英] How do you handle a thread that has a hung call?

查看:126
本文介绍了你如何处理,有一个电话挂起一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程熄灭并试图建立连接。在线程,我让第三方库的呼叫。有时,这个调用挂起,永不返回。在UI线程,我希望能够通过中止线程,这应该放弃对第三方库红呼吁取消连接尝试。

I have a thread that goes out and attempts to make a connection. In the thread, I make a call to a third party library. Sometimes, this call hangs, and never returns. On the UI thread, I want to be able to cancel the connection attempt by aborting the thread, which should abort the hung call to the third party library.

我叫Thread.Abort的,但现在已经读了Thread.Abort的只能当控制返回到托管code。我观察到,这是真的,因为线程永远不会中止,而现在我已经坐的Thread.join十分钟。我应该怎么做这个挂起线程?如果我只是空的基准,继续前进?我想是尽可能干净 -

I've called Thread.Abort, but have now read that Thread.Abort only works when control returns to managed code. I have observed that this is true, because the thread never aborts, and I've been sitting on Thread.Join for ten minutes now. What should I do with this hung thread? Should I just null the reference and move on? I'd like to be as clean as possible--

推荐答案

这个功能的第三方库没有超时的的取消功能?如果是这样,那是pretty设计很差。有没有打算在这里是任何pretty解决方案,记错...

This function in your third-party library doesn't have a timeout or cancel function? If so, that's pretty poor design. There's not going to be any pretty solution here, methinks...

不幸的是,有没有办法,你要避开它,短期使用Win32 API来手动终止线程,这肯定是的不会的清洁。但是,如果此第三方库不给你任何其他选项,它可能会做的事。该 TerminateThread 功能什么,你会想用,但观察警告!要获得线程ID传递给这个函数,你必须使用另一种Win32 API调用(即类不直接暴露它)。这里的做法将是挥发性类变量的值设置为 <$ C的结果$ C> GetCurrentThreadId 在托管线程方法开始,然后用这个线程ID后面来终止线程​​。

Unfortunately, there's no way you're going to get around it, short of using the Win32 API to kill the thread manually, which is certainly not going to be clean. However, if this third-party library is not giving you any other options, it may be the thing to do. The TerminateThread function is what you'll want to use, but observe the warning! To get the thread ID to pass to this function, you have to use another Win32 API call (the Thread class doesn't expose it directly). The approach here will be to set the value of a volatile class variable to the result of GetCurrentThreadId at the start of the managed thread method, and then use this thread ID later to terminate the thread.

这篇关于你如何处理,有一个电话挂起一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆