我有一个带有多个 GUI 线程的 winforms 应用程序。我希望他们能够访问彼此的线程对象,而不必单独跟踪该信息。
.NET 中是否有一个函数可以提供 winforms 控件或窗口对象,并返回线程?或者我可以为 threadID pinvoke API 中的函数?
(请不要评论说我应该用另一种方式来做......而且这也不是关于跨线程窗口操作。)
Thanks!
Edit
对于那些出于某种原因相信我的斜体文字的人,恭喜,你被录取了!!问题是这样的:
“应用程序因完全锁定而在野外崩溃,也就是说,它停止响应。非常间歇性,并试图调试它,它似乎永远不会发生。”
那么做什么呢?在程序中安装一个选项,用户可以在我们的指导下激活该选项,从而从同一应用程序中的另一个 GUI 线程,在主 GUI 线程上执行 thread.abort,然后我们可以查看错误日志中的调用堆栈。 Viola 在不到一天的时间内发现了一个无法调试的错误。 (现在停下来,这与滥用多线程无关:-)
我承认我几乎没有问这个,我这样做的原因是我可以看到对主窗体的对象引用,但它的线程没有任何对象引用。我正在给 Chris Shain 答案,这是一种快速的方法,不幸的是,当线程挂起时,我将无法执行调用(它也会挂起)。进一步挖掘发现了 GetWindowThreadProcessId API 调用。但它是一个非托管线程 ID,显然将其转换为托管线程 ID 会很复杂。
所以我硬着头皮放入了对主 UI 线程的全局引用。本来想发帖的,只是还没写。
现在如果你能原谅 VB...
在主公共模块/静态类中:
Public GUIThread As Threading.Thread
Sub Main()
'' // Create app main window
ShellForm = New frmShell
'' // Save main GUI Thread for abort routine
GUIThread = Threading.Thread.CurrentThread
If GetSetting("MyApp", "Testing", "CrashDebug", "False") = "True" Then
'' // DO NOT run the pgm. like this normally - with try/catch around
'' // Application.Run - or uncaught errors will kill the whole app!!!
Try
'' // This is the other of the ‘Multiple GUI threads’ I talked
'' // about in the Orig Post.
Dim t As New Threading.Thread(AddressOf StartCrashDebug)
t.Start()
Application.Run(ShellForm)
Catch ex As Exception
'' // This error routine passes errors off to another thread which
'' // logs them (and also shows messages)
MyLogError(ex, "CrashDebug - Main Window blew up")
End Try
Else
'' // Normal mode - uncaught errors will get caught by UnhandledException,
'' // logged, and Winforms will keep the GUI alive (since we _do_ care
'' // more about users than computers right ;-)
Application.Run(ShellForm)
End If
End Sub
Sub StartCrashDebug()
Dim f As New frmCrashFinder
'' // Starting a window like this on a separate thread makes it ‘Another
'' // GUI thread’ for winforms, by design
Application.Run(f)
End Sub
在“中止”WinForm 中:
Public Class frmCrashFinder
Inherits Windows.Form
Private Sub Abort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Abort.Click
GUIThread.Abort()
End Sub
End Class