检测在 C# 库中的主线程中运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/225545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting running in Main Thread in C# library
提问by stachu
I'm creating a C# dll, which is going to be used by others developers in WinForms. For some reasons, I want to detect, if methods from this library, are called from Main (GUI) Thread and warn developer he has done such a thing (ie. in log file). Is there any reasonable way to detect calling method from main thread? Remember I have no access to WinForm application.
我正在创建一个 C# dll,它将被 WinForms 中的其他开发人员使用。出于某些原因,我想检测这个库中的方法是否从主(GUI)线程调用并警告开发人员他做了这样的事情(即在日志文件中)。有什么合理的方法可以检测主线程的调用方法吗?请记住,我无权访问 WinForm 应用程序。
采纳答案by ageektrapped
An easy solution in this case is to declare a static control in the library assembly that is created on the Main UI thread. If you want to detect if the library is called from the main thread, then use the following
在这种情况下,一个简单的解决方案是在主 UI 线程上创建的库程序集中声明一个静态控件。如果要检测库是否从主线程调用,则使用以下
if (MyLibraryControl.InvokeRequired)
//do your thing here
回答by Marc Gravell
The simplest option (if you have a form/control handy) is to check InvokeRequired.
最简单的选择(如果您有一个方便的表单/控件)是检查 InvokeRequired。
In the absence if that, you could try using SynchronizationContext
to simulate a Post or Send, checking what thread that happens on? Calling Send or Post will switch to the UI thread.
如果没有,您可以尝试使用SynchronizationContext
模拟 Post 或 Send,检查发生在哪个线程上?调用 Send 或 Post 将切换到 UI 线程。