Hanging on by a …

THREAD !!!!!!!!!!

yeah ok bad joke. I’ve been so dang busy with studying and work that I just haven’t had a reasonable chance to write any updates for the C# on macOS series.

But now that my Canadian Ski Patrol exams are done I can get back to some fun.

How to make our little project use a thread instead of a timer. The biggest place in the project you might notice this is in the level indicator.

Right now when you press & hold a menu item the updates to the level indicator will pause until you release the menu item. It sure would be nice to not have that occur.

And, the reality is that since we are using C#, most of what we need is already built in, or easy to acquire.

We’ll need to add a Nuget package

We’ll need to add the Xamarin Essentials package

And we’ll want to add a using clause so the compiler is alerted to the fact we’re going to use the Xamarin.Essentials package.

We need to declare a variable to hold out thread instance

We’ll change the window SetUpControl method to NOT create a timer but instead create a Thread.

This new line creates the thread and tell it what method to call when the thread runs. This method is one that gets called ASYNCHRONOUSLY – so it has some slightly special set up.

 private async void Thread_Action()
 {
    while (true)
    {
       await Xamarin.Essentials.MainThread.InvokeOnMainThreadAsync( () =>      Update_Indicator() );
       System.Threading.Thread.Sleep(100);
    }
}

Note the ASYNC keyword on this method – thats the entire “special set up” 🙂

The other thing I’ve done is refactored the old timer code so the thread and timer can both use the same method to update the indicator.

The only remaining thing to do now is start the thread running right where we used to have the Timer getting started.

Now because we have added some C# runtime references, and a using clause for System.Threading, you may see an error like

You can have VS take you right to the location of the error by right clicking the error and choosing “Go To Task”

We can correct the issue by simply fully qualifying the Type name to Einhugur.Threading.Timer

Once fixed you should be able to run and, note what when you press & hold the Edit item in the menu bar the level indicator continues to move up & down unlike what it did with the timer.

The speed with which the indicator moves up and down can be adjusted by changing the sleep value for he thread. The shorter the sleep period the faster indicator will update.

Once again – the project in its current state

One Reply to “Hanging on by a …”

Comments are closed.