检测C#库中主线程的运行

时间:2022-04-07 21:00:12

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应用程序。

2 个解决方案

#1


17  

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

#2


2  

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线程。

#1


17  

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

#2


2  

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线程。