The only reason you would need to check the IsMainThread property is if you have branching logic that does something different based on the thread. There is negligible overhead in doing so. Therefore, if the code you run is the same, regardless of the main or secondary thread, simply call BeginInvokeOnMainThread without checking if it's required. If the code is running on a secondary thread, BeginInvokeOnMainThread invokes the provided method on the main thread. If the code is running on the main thread, BeginInvokeOnMainThread just calls the provided method directly. BeginInvokeOnMainThread itself tests if the current code is running on the main thread or not. If it isn't running on the main thread, the method is passed to BeginInvokeOnMainThread: if (MainThread.IsMainThread) For example, the following code uses the IsMainThread to detect if the MyMainThreadCode method should be called directly if the code is running on the main thread. It's logical to assume that you need to determine if the code is running on the main thread before calling MainThread.BeginInvokeOnMainThread. The MainThread.IsMainThread property returns true if the code calling the property is running on the main thread, and false if it isn't. With the MainThread class, you can determine if the current code is running on the main thread. MainThread.BeginInvokeOnMainThread(MyMainThreadCode) It is also possible to define a separate method for the code, and then call that code with the BeginInvokeOnMainThread method: void MyMainThreadCode() The argument is an Action object, which is simply a method with no arguments and no return value: MainThread.BeginInvokeOnMainThread(() => To run code on the main thread, call the static MainThread.BeginInvokeOnMainThread method. If the event handler needs to access user-interface elements, it must invoke code on the main thread. All sensors might return information on a secondary thread when used with faster sensing speeds. When is it requiredĪpplications sometimes need to use events that call the event handler on a secondary thread, such as the Accelerometer or Compass sensors. The MainThread class is available in the namespace. The disadvantage of this model is that all code that accesses user interface elements must run on the application's main thread. ![]() This thread is often called the main thread, the user-interface thread, or the UI thread. This model is necessary to properly serialize user-interface events, including keystrokes and touch input. Most operating systems use a single-threading model for code involving the user interface. NET Multi-platform App UI (.NET MAUI) MainThread class to run code on the main UI thread. ![]() ![]() This article describes how you can use the.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |