Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a function on the main app from a background task

I am currently developing an HMI that must connect to a remote server on the same network to be able to start. To do this, I use the splash screen feature of the UWP platform that allows me to simulate a loading page.

My problem is that I have to receive the word "start" by the server to be able to unlock my splash screen and pass on the application.

So I tried to call this function directly from my background but inevitably it does not work.

The functions to exit the splash screen:

void DismissedEventHandler(SplashScreen sender, object e)
{
    dismissed = true;
}

public void DismissExtendedSplash()
{
    rootFrame.Navigate(typeof(MainPage));
    Window.Current.Content = rootFrame;
}

void DismissSplashButton_Click(object sender, RoutedEventArgs e)
{
    DismissExtendedSplash();
}

SocketActivtyTask:

case SocketActivityTriggerReason.SocketActivity:
   var socket = socketInformation.StreamSocket;
   DataReader reader = new DataReader(socket.InputStream);
   reader.InputStreamOptions = InputStreamOptions.Partial;
   await reader.LoadAsync(250);
   var dataString = reader.ReadString(reader.UnconsumedBufferLength);

   try
   {
      if (dataString.Equals("Start"))
      {
          Debug.WriteLine("Lancement OK.");
          DismissExtendedSplash();
      }
    }
    catch
    {
          Debug.WriteLine("Lancement FAIL.");
    }
   }

How can I make it work ?

An additional question, how to cancel the background task when closing the application?

like image 945
ValentinDP Avatar asked Mar 18 '26 09:03

ValentinDP


1 Answers

Never do any tasks that take time from the application thread. That is a sure way to introduce performance problems (at best) or deadlocks (at worst) into your application. Use a BackgroundWorker for tasks that will take time. Use the RunWorkerCompleted event handler to update your application's UI when the task is done.

Here is a relatively simple example of implementing the BackgroundWorker class: https://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners

like image 78
Jim Fell Avatar answered Mar 20 '26 23:03

Jim Fell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!