Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if my current thread is the UI thread?

I'm working on a user control for UWP and it updates some of its visuals upon certain calls. However, since the core .NET library has been shifted around and the threading classes have been severely cut back, I don't know how to identify from the method in the user control if the calling thread is the UI thread or not so it knows whether or not to use the dispatcher to change a dependency property.

Anyone know how to do this?

EDIT: The dispatcher functionally can be "invoked" async fine on the UI thread - however, I really don't know if this is a good idea - to try to invoke on the main thread from the main thread via the dispatcher. If anyone has a reason this is fine or bad, that would also contribute to answering the question. If there's no reason to not use the dispatcher on the main thread, then I guess there's no problem.

like image 437
ThisHandleNotInUse Avatar asked Aug 20 '15 02:08

ThisHandleNotInUse


People also ask

Is UI thread same as main thread?

UI Thread and Main Thread are same only in Android. The Main thread, that is responsible for handling the UI events like Draw, Listen and receive the UI events. Ans also it is responsible for interact with running components of the UI toolkit for the corresponding application that belongs to.

How can you tell if a thread is main thread?

if(Looper. getMainLooper(). getThread() == Thread. currentThread()) { // Current Thread is Main Thread. }

What is the UI thread?

User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.

Which method is used to know the current state of a thread?

The method currentThread() of the Thread class can be used to obtain the current thread.


1 Answers

I have found the solution...

CoreDispatcher.HasThreadAccess returns a bool indicating if you are on the UI thread or not.

like image 125
ThisHandleNotInUse Avatar answered Sep 24 '22 02:09

ThisHandleNotInUse