0

I have tried this code to make sure the task can only run once:

    static bool running = false;

public void Run(IBackgroundTaskInstance taskInstance)
{
    if (running)
    {
        makeToast("Cancelled because another already running");
        return;
    }

    running = true;
    // Do stuff.
}

But it seems like running stays true if even if all instances of a task are terminated. Setting it to false on cancelation also isn't reliable, as the cancelation method is not always called (unexpected system shutdown, crash...).

Is there a way to if other instances are running within the background task itself?

Dodeius
  • 125
  • 1
  • 10
  • 1
    First of all, add a lock on writable static. Maybe also try catch your work, to set running fo false if job failed. – LeBigCat Dec 07 '18 at 09:57
  • @LeBigCat the lock only helps with writing, right? – Dodeius Dec 07 '18 at 16:34
  • It s a lillte more complicated: read this link https://stackoverflow.com/questions/1668719/c-sharp-multi-threading-acquire-read-lock-necessary – LeBigCat Dec 07 '18 at 16:48

1 Answers1

0

I think you could use LocalSettings to record the background task run times. And local setting data will stored in disk and it is persistence.

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["exampleSetting"] = "Hello Windows";

Before next background task run, you could retrieve the data, if it is not null, the task has been run.

Object value = localSettings.Values["exampleSetting"];

if (value == null)
{
    // No data.
}
else
{
    // Access data in value.
}

// Delete a simple setting.
localSettings.Values.Remove("exampleSetting");
Nico Zhu
  • 32,367
  • 2
  • 15
  • 36