C# 线程。在具有超时的多个线程上进行连接
我有一个线程数组,我想用一个超时来连接所有线程(即,看看它们是否都在某个超时内完成)。我正在寻找与WaitForMultipleObjects等价的东西,或者寻找一种将线程句柄传递到WaitHandle.WaitAll的方法,但是在BCL中似乎找不到任何符合我要求的东西 我当然可以遍历所有线程(见下文),但这意味着整个函数可能需要timeout*threads.Count才能返回C# 线程。在具有超时的多个线程上进行连接,c#,multithreading,C#,Multithreading,我有一个线程数组,我想用一个超时来连接所有线程(即,看看它们是否都在某个超时内完成)。我正在寻找与WaitForMultipleObjects等价的东西,或者寻找一种将线程句柄传递到WaitHandle.WaitAll的方法,但是在BCL中似乎找不到任何符合我要求的东西 我当然可以遍历所有线程(见下文),但这意味着整个函数可能需要timeout*threads.Count才能返回 private Thread[] threads; public bool HaveAllThreadsFinis
private Thread[] threads;
public bool HaveAllThreadsFinished(Timespan timeout)
{
foreach (var thread in threads)
{
if (!thread.Join(timeout))
{
return false;
}
}
return true;
}
但在此循环中,您可以减少超时值:
private Thread[] threads;
public bool HaveAllThreadsFinished(Timespan timeout)
{
foreach (var thread in threads)
{
Stopwatch sw = Stopwatch.StartNew();
if (!thread.Join(timeout))
{
return false;
}
sw.Stop();
timeout -= Timespan.FromMiliseconds(sw.ElapsedMiliseconds);
}
return true;
}
请参见我建议您首先计算“死区时间”,然后使用当前时间和原始死区时间之间的差异在线程上循环:
private Thread[] threads;
public bool HaveAllThreadsFinished(TimeSpan timeout)
{
DateTime end = DateTime.UtcNow + timeout;
foreach (var thread in threads)
{
timeout = end - DateTime.UtcNow;
if (timeout <= TimeSpan.Zero || !thread.Join(timeout))
{
return false;
}
}
return true;
}
私有线程[]个线程;
public bool HaveAllThreadsFinished(TimeSpan超时)
{
DateTime end=DateTime.UtcNow+超时;
foreach(线程中的var线程)
{
timeout=end-DateTime.UtcNow;
if(timeout)认为我可能最终不得不这样做,但希望可能已经有一个很好的BCL函数为我做了这件事
private Thread[] threads;
public bool HaveAllThreadsFinished(TimeSpan timeout)
{
DateTime end = DateTime.UtcNow + timeout;
foreach (var thread in threads)
{
timeout = end - DateTime.UtcNow;
if (timeout <= TimeSpan.Zero || !thread.Join(timeout))
{
return false;
}
}
return true;
}