在C#中的线程超时 [英] Thread timeout in c#

查看:835
本文介绍了在C#中的线程超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新在C#中的线程。
反正是有设定一个线程超时而不会阻塞调用线程(在C#3.5)?



如果不是,它是合乎逻辑的执行功能使用一个线程,该函数内创建一个线程,并加入它来克服这个主线程阻塞问题?为了说明:

 公共无效的主要():<​​/ p> 

而不是
{
...
螺纹锁而=新主题(新的ThreadStart(targetObj.targetFunc));
thrd1.Start();
thrd1.Join();

}



使用类似:

 公共无效的main()
{
...
螺纹锁而=新主题(新的ThreadStart(middleObj 。服务员));
thrd1.Start();

}

//而在middleObj.waiter():
公共无效服务员()
{
螺纹对于thrd2 =新主题(新的ThreadStart(targetObj.targetFunc));
thrd2.Start();
thrd2.Join();
}


解决方案

我检查和简单,这样做的最全面的方式是我的问题的说明中提到的解决方案。有中间级的线程可以轻松地等待,而不在主线程任何中断第二个线程;它可以杀死所述第二线程,如果它没有在规定的时间内作出响应。这正是我需要的。我用它和它的工作没有问题。


I'm new to threading in C#. Is there anyway of setting a timeout for a thread without blocking the calling thread (in C# 3.5)?

If not, is it logical to execute a function using a thread and within that function create a thread and join it to overcome this main thread blocking issue? To illustrate:

Instead of:

Public void main()
{
        ...
        Thread thrd1 = new Thread(new ThreadStart(targetObj.targetFunc));
        thrd1.Start();
        thrd1.Join();
        ...
}

Using something like:

Public void main()
{
        ...
        Thread thrd1 = new Thread(new ThreadStart(middleObj.waiter));
        thrd1.Start();
        ...
}

//And in the middleObj.waiter():
Public void waiter()
{
        Thread thrd2 = new Thread(new ThreadStart(targetObj.targetFunc));
        thrd2.Start();
        thrd2.Join();
}

解决方案

I checked and the simplest and most comprehensive way of doing it was the solution I mentioned in the description of the question. A middle level thread can easily wait for the second thread without any interruption over the main thread; and it can kill the second thread if it does not respond within the required time. That's exactly what I needed. I used it and it worked without a problem.

这篇关于在C#中的线程超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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