Tertium Tertium - 3 years ago 150
C# Question

Get Windows 8.1 universal app state / public variable access from its winrt component

I have an Universal Windows Platform app and for background checkings I use winrt component (separate project in solution). I register it correctly and system launches my winrt class every 15 minutes. The problem is that my app uses the same files and makes the same checks that background checker does. So I need to know is my app alive (background or foreground) to skip background check to avoid multithread file access.
Is there any way to get access to state of my app from winrt component, or query system does my app active?

Answer Source

Since the Anniversary update, it is now possible to run background tasks from within the same process as the main app. Both the background task and the main app share the same memory. See Create and register a single-process background task for information on how to do this.

If you want to keep the background task in a separate process to the main app, then you can use a named EventWaitHandle:

Foreground app code

// Keep this handle alive for the duration of your app
eventHandle = new EventWaitHandle(true, EventResetMode.ManualReset, "MyApp");

Background app code

EventWaitHandle handle;

if (EventWaitHandle.TryOpenExisting("MyApp", out handle)) {
    // Foreground app is running
} else {
    // Foreground app is not running

You need to be mindful of possible race conditions here (if that is a problem for your situation). You could probably make better use of the EventWaitHandle to synchronize whatever file task it is both processes need to do.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download