像这样(在C#中)收集外来ProcessThread
的所有Process
的属性时:
process.Threads.OfType<ProcessThread>()
.Aggregate($"Native Threads Report:{Environment.NewLine}\t Id StartTime PrivilegedProcessorTime TotalProcessorTime BasePriority ThreadState{Environment.NewLine}\t{new string('-', 97)}",
(a_Accu, a_Th) => a_Accu += GetThreadInfos(a_Th));
一切正常,直到这些线程中的一个(或多个)似乎退出为止。然后在GetThreadInfos()
方法中发生InvalidOperationException
:
/// <summary>Returns property informations of the ProcessThread, formatted as text table</summary>
private static string GetThreadInfos(ProcessThread p_Th)
{
string l_Id = string.Empty;
System.Diagnostics.ThreadState l_State = System.Diagnostics.ThreadState.Unknown;
int l_BasePriority = -1;
try
{
l_Id = p_Th.Id.ToString().PadLeft(6);
l_State = p_Th.ThreadState;
l_BasePriority = p_Th.BasePriority;
return $"{Environment.NewLine}\t{l_Id} {p_Th.StartTime.ToISO8601()} {p_Th.PrivilegedProcessorTime.ToString().PadRight(23)} {p_Th.TotalProcessorTime.ToString().PadRight(18)} {l_BasePriority.ToString().PadRight(12)} {p_Th.ThreadState.ToString()}";
}
catch (Exception)
{
return $"{Environment.NewLine}\t{l_Id} [Thread access error]{string.Empty.PadLeft(23)} {string.Empty.PadLeft(18)} {l_BasePriority.ToString().PadRight(12)} {l_State.ToString()}";
}
}
异常消息是:
我发现了这个异常,发现我仍然可以访问哪些属性并进行了适当的打印输出,因此可以正常工作。
但是它经常发生,并且会向应用程序输出垃圾邮件。
因此,问题是:可以避免例外吗?是否可以查询线程是否已经退出?