How to find out if code works in ui thread or work thread (MFC Visual C ++)

I have a function called from different threads in an application. I need to know if the thread executing the code is the main thread (ui thread) or workflow.

Any suggestion?

Thanks.

+4
source share
3 answers

Use the following code if you are using the MFC application.

if(GetCurrentThreadId() == AfxGetApp()->m_nThreadID) { //Main Thread } else { //Not Main Thread } 
+11
source

Use GetCurrentThread () or GetCurrentTreadId () and compare it with the known HANDLE or id of the main thread.

Can't have multiple user interface threads?

Of course, maybe, but only one main thread ui.

Ok But is there any way to find out the HANDLE or main thread identifier from this code? I mean something like GetMainThread or GetMainThreadID. I would like not to modify other parts of the application (if possible). BTW, Thanks for your reply.

Sorry, I had lunch and you have already received your answer. But can also answer. GetCurrentThreadId () can, of course, be used at runtime of your main ui thread and cached for later comparison. Somewhere during the execution of your application there will be only one thread, for example. in WinMain () before creating any other thread.

Greetings!

+5
source

AfxGetApp () → GetMainWnd ()

will return the same as AfxGetMainWnd () will return if called from the main thread.

0
source

All Articles