ValentinDP
ValentinDP

Reputation: 323

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?

Upvotes: 3

Views: 410

Answers (2)

sayah imad
sayah imad

Reputation: 1553

I think in your case, you should use what we call BackgroundTask as your best practice. To do this, you need first implement IBackgroundTask in your application, which will allow you to trigger a specific event .

MSDN Link https://learn.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task

Upvotes: 0

Jim Fell
Jim Fell

Reputation: 14256

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

Upvotes: 3

Related Questions