public bool TryLockAndGet <T>(string lockKey, int msTimeout, Func <T> get, out T output) { Mutex m = null; output = default(T); try { // Global/Local Mutex - https://msdn.microsoft.com/en-us/library/f55ddskf(v=vs.110).aspx m = new Mutex(false, GLOBAL_KEYWORD + lockKey); _logger.Log("Waiting for a turn"); if (m.WaitOne(msTimeout)) { if (get != null) { _logger.Log("Got the lock, working on something now"); output = get(); } _logger.Log("Done, releasing the lock"); m?.ReleaseMutex(); return(true); // lock was acquired successfully } } catch (Exception ex) { _logger.Log("Error: {0}", ex.Message); } finally { m?.Dispose(); } return(false); // lock was not acquired }
private void wpfApp_Exit(object sender, ExitEventArgs e) { try { Task mutexCleanup = new Task(() => { if (HasMutex) { s_mutex?.Close(); s_mutex?.Dispose(); s_mutex = null; } else if (!GainMutexTask.IsCompleted) { AbortMutex = true; GainMutexTask.Wait(); } }); mutexCleanup.Start(); mutexCleanup.Wait(); } catch (Exception ex) { LogHelper.LogException(ex, ex.Message); } finally { LogHelper.LogMessage(LogLevel.Info, string.Format("Shutdown Application {0}", Assembly.GetExecutingAssembly().FullName)); } }
public RequestRelease Execute() { Mutex mutex = null; try { mutex = new Mutex(false, _id); try { if (!mutex.WaitOne(_timeout ?? TimeSpan.Zero, false)) { mutex.Dispose(); return(null); } } catch (AbandonedMutexException) { //Nothing } return(new RequestRelease(mutex)); } catch { mutex?.Dispose(); return(null); } }
/// <summary> /// Starts a JSON-RPC thread to handle client calls. /// </summary> /// <param name="threadsDoneEvent">The event to set when all RPC threads are finished.</param> /// <param name="commandLineInformation">The command line information (debug on start, pipe name, etc.).</param> /// <remarks> /// This code only catches exceptions it expects to encounter. If there is some other /// type of exception, can't start thread, can't create pipe, etc., then /// we want the process to crash so we can figure out the conditions under which /// it occurs and address it. /// The event source is owned by the new thread, and it must dispose of it when finished. /// </remarks> private static void CreateRPCServerThread(EventWaitHandle threadsDoneEvent, ServerStartParameters commandLineInformation) { if (commandLineInformation.DebugOnStart) { Debugger.Launch(); } new Thread(new ThreadStart(() => { Interlocked.Increment(ref rpcThreads); StartJsonRpcServer(commandLineInformation); var numberOfThreadsRemaining = Interlocked.Decrement(ref rpcThreads); // Release our mutex is trying to reduce the chance that while we are exiting // another process is trying to send command line information to us. if (numberOfThreadsRemaining == 0) { alreadyRunningMutex?.Dispose(); } if (numberOfThreadsRemaining == 0) { // We need to send our events and dispose our event source // before signaling all threads done. Otherwise // the main thread exits and we lose events. threadsDoneEvent.Set(); } })).Start(); }
protected override void OnExit(ExitEventArgs e) { // Shut down threads ProcessManager.Stop(); InputMapper.Stop(); ControllerManager.Stop(); Overlay.Stop(); // Save settings WoWmapper.Properties.Settings.Default.Save(); try { // Dispose mutex _mutex?.ReleaseMutex(); _mutex?.Dispose(); } catch { } _notifyIcon.Visible = false; _notifyIcon.Dispose(); // Exit application base.OnExit(e); }
protected virtual void Dispose(bool disposing) { if (disposing) { mutex?.Dispose(); } }
protected override void OnExit(ExitEventArgs e) { _mutex?.Dispose(); Logger.Current.Log("application stopped"); base.OnExit(e); }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing) { _tmrHouseKeeping.Elapsed -= (s, e) => DoHouseKeeping(); _tmrProcessFile.Elapsed -= (s, e) => ProcessDroppedFileHelper(); _configFileMonitor.Changed -= (s, e) => ReloadAndApplyConfigChanges(); _mainWatcher.Changed -= (s, e) => ProcessDroppedJarFile(s, e); _messenger.Notify -= MessengerNotification; _components?.Dispose(); _configFileMonitor.EnableRaisingEvents = false; _configFileMonitor?.Dispose(); _mainWatcher.EnableRaisingEvents = false; _mainWatcher?.Dispose(); _perfCounters?.Dispose(); _jniBridgeManager?.Dispose(); _protectMutex?.Dispose(); _tmrHouseKeeping?.Dispose(); _tmrProcessFile?.Dispose(); // Let's dispose of service hosts (if any) var hosts = HostManager?.DynamicHosts?.ToList(); hosts?.ForEach(_ => _.Value?.Close()); } base.Dispose(disposing); }
protected override void OnExit(ExitEventArgs e) { _notifyIcon?.Dispose(); _appMutex?.Dispose(); Log.Logger.Information("==== Exit ===="); base.OnExit(e); }
public void Dispose() { if (_acquired) { _mutex.ReleaseMutex(); } _mutex?.Dispose(); }
protected override void OnExit(ExitEventArgs e) { Mutex?.Close(); Mutex?.Dispose(); Mutex = null; base.OnExit(e); }
private static void Close() { if (!_isClosed) { _isClosed = true; _sMutexApp?.Dispose(); } }
private void OnExit() { if (_mutexAcquired) { _mutex.ReleaseMutex(); } _mutex?.Dispose(); RestartIfNeeded(); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { Mutex?.Dispose(); } }
private static void Close() { if (!_isClosed) { _isClosed = true; HttpServer.Stop(); _sMutexApp?.Dispose(); } }
private void CleanUp() { appMutex?.Dispose(); notifyIcon?.Dispose(); taskbarManager?.Dispose(); shortcutManager?.Dispose(); windowManager?.Dispose(); configurationManager?.Dispose(); }
public static void Exit() { if (!_isClosed) { _isClosed = true; _sMutexApp?.Dispose(); } Environment.Exit(0); }
protected override void OnExit(ExitEventArgs e) { _nightLightDetection?.Stop(); base.OnExit(e); _adrilightMutex?.Dispose(); LogManager.Shutdown(); }
internal static bool RealizarLeituraRota() { do { string sourcePath = DirArq; string[] ConteudoRota = new string[30]; try { FileInfo fileInfo = new FileInfo(sourcePath); bool mutexOwned = false; Mutex mutex = null; try { mutex = new Mutex(true, "teste", out mutexOwned); if (!mutexOwned) { mutex.WaitOne(); } ConteudoRota = File.ReadAllLines(sourcePath); } finally { mutex?.ReleaseMutex(); mutex?.Dispose(); mutex = null; } } catch (IOException e) { Console.WriteLine("Ocorreu um erro"); Console.WriteLine(e.Message); } if (String.Compare(ConteudoRota[0], "v") == 0 && String.Compare(ConteudoRota[ConteudoRota.Length - 1], "v") == 0) { for (int i = 0; i < ConteudoRota.Length - 2; i++) { if (ConteudoRota[i + 1].Contains('i') || ConteudoRota[i + 1].Contains('f')) { if (ConteudoRota[i + 1].Contains('i')) { PosInicio = int.Parse(ConteudoRota[i + 1].Trim(charsToTrim)); } else { PosFinal = int.Parse(ConteudoRota[i + 1].Trim(charsToTrim)); } } Rota.Add(int.Parse(ConteudoRota[i + 1].Trim(charsToTrim))); } return(true); } } while (true); }
/// <summary> /// Handles the application exit, including the state handling. /// </summary> /// <param name="e"></param> protected override void OnExit(ExitEventArgs e) { // Save current state on exit DI.Application.Save(); // Dispose mutex Mutex?.Dispose(); base.OnExit(e); }
private static void Close() { if (!_isClosed) { _isClosed = true; HttpServer.Stop(); s_mutexApp?.Dispose(); NotifyIcon?.Dispose(); } }
protected override void Dispose(bool disposing) { if (IsDisposed) { return; } _mutex?.ReleaseMutex(); _mutex?.Dispose(); base.Dispose(disposing); }
public static void Exit() { if (!_isClosed) { _isClosed = true; RaiseEvent(new AppExitEvent()); RpcRoot.RpcUser?.Logout(); NTMinerConsole.Free(); _sMutexApp?.Dispose(); Environment.Exit(0); } }
public static void Exit() { if (!_isClosed) { _isClosed = true; VirtualRoot.RaiseEvent(new AppExitEvent()); _sMutexApp?.Dispose(); Environment.Exit(0); } }
protected override void OnExit(ExitEventArgs e) { mutex?.Close(); mutex?.Dispose(); mutex = null; UnityContainer.Dispose(); base.OnExit(e); }
protected override void OnExit(ExitEventArgs e) { if (mutexAccessed) { mutex?.ReleaseMutex(); } mutex?.Dispose(); mutex = null; base.OnExit(e); }
/// <summary> /// Runs the <see cref="IDiscordBot"/>. /// </summary> private async Task <int> RunAsync() { discordBot.LoadConfig(); if (allowMultipleInstances || !SingleInstanceCheck()) { return(0); } services = await discordBot.InitializeAsync(ConfigureServices()).ConfigureAwait(false); discordBot.ShuttingDown += OnShuttingDownAsync; // Start the startup service services.GetRequiredService <DiscordSocketClient>().Ready += OnReadyAsync; await services.GetRequiredService <StartupService>().StartAsync().ConfigureAwait(false); await discordBot.StartAsync().ConfigureAwait(false); // Keep the program alive until shutdown/restart shutdownEvent.WaitOne(); // Wait a moment to prevent wonkey Discord message output //await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false); // Allow time to go invisible await Task.Delay(TimeSpan.FromSeconds(1.5)).ConfigureAwait(false); await services.GetRequiredService <DiscordSocketClient>().StopAsync().ConfigureAwait(false); mutex?.Dispose(); services.Dispose(); if (shutdownMode == ShutdownMode.Restart) { if (isRunningFromDaemon) { return(RestartExitCode); } // Restart right here, right now string arguments = string.Join(" ", args.Select(a => $"\"{a}\"")); #if NETSTANDARD2_0 Process.Start("dotnet", $"{(Assembly.GetEntryAssembly().Location)} {arguments}"); #else Process.Start(Assembly.GetEntryAssembly().Location, arguments); #endif // Double clear is needed to ensure *actually cleared* console. It's weird. Console.Clear(); Console.Clear(); Environment.Exit(0); } return(0); }
protected virtual void Dispose(bool disposing) { if (!disposed) { _Mutex?.Close(); _Mutex?.Dispose(); _Mutex = null; disposed = true; } }
public async Task OnExitAsync() { foreach (var token in _subscriptionTokens) { Messenger.Unsubscribe(token); } await Container.DisposeAsync().ConfigureAwait(false); _mutex?.Dispose(); }
public bool Acquire() { if (_acquired) { throw new InvalidOperationException($"DB mutex '{MutexName}' is already acquired."); } try { _dbMutex?.Dispose(); _dbMutex = new Mutex(initiallyOwned: true, name: MutexName, createdNew: out _acquired); _dbMutex.WaitOne(TimeSpan.FromSeconds(5)); } catch (AbandonedMutexException exc) { Log.Warning(exc, "DB mutex '{mutex}' is said to be abandoned. " + "Probably previous instance of server was terminated abruptly.", MutexName); } return(_acquired); }
public static void DisposeTest() { var name = "MyCrazyMutexName" + Guid.NewGuid(); var handle = new Mutex(true, name); handle.Dispose(); Assert.False(Mutex.TryOpenExisting(name, out handle)); // TODO: Better exceptions on .NET Native //Assert.Throws<ObjectDisposedException>(() => handle.WaitOne(0)); }
public bool PosTest1() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest1: WaitOne returns true when current instance receives a signal"); try { do { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(SignalMutex)); thread.Start(); if (m_Mutex.WaitOne() != true) { TestLibrary.TestFramework.LogError("001", "WaitOne returns false when current instance receives a signal."); retVal = false; break; } m_Mutex.ReleaseMutex(); } while (false); // do } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } m_Mutex.Dispose(); } return retVal; }
private static void Main(string[] args) { //uninstall? string[] arguments = Environment.GetCommandLineArgs(); foreach (string argument in arguments) { if (argument.Split('=')[0].ToLower() == "/u") { string guid = argument.Split('=')[1]; string path = Environment.GetFolderPath(Environment.SpecialFolder.System); var si = new ProcessStartInfo(path + "/msiexec.exe", "/x " + guid); Process.Start(si); Application.Exit(); return; } } try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); bool firstInstance = true; //Mutex = new Mutex(false, "iSpy", out firstInstance); var me = Process.GetCurrentProcess(); var arrProcesses = Process.GetProcessesByName(me.ProcessName); if (arrProcesses.Length > 1) { File.WriteAllText(AppDataPath + "external_command.txt", "showform"); //ensures pickup by filesystemwatcher Thread.Sleep(1000); firstInstance = false; } string executableName = Application.ExecutablePath; var executableFileInfo = new FileInfo(executableName); ExecutableDirectory = executableFileInfo.DirectoryName; bool ei = (!Directory.Exists(AppDataPath) || !Directory.Exists(AppDataPath + @"XML\") || !File.Exists(AppDataPath + @"XML\config.xml")); if (ei) EnsureInstall(true); bool silentstartup = false; string command = ""; if (args.Length > 0) { //if (args[0].ToLower().Trim() == "-firstrun" && !ei) // EnsureInstall(false); if (args[0].ToLower().Trim() == "-reset" && !ei) { if (firstInstance) { if ( MessageBox.Show("Reset iSpy? This will overwrite all your settings.", "Confirm", MessageBoxButtons.OKCancel) == DialogResult.OK) EnsureInstall(true); } else { MessageBox.Show("Please exit iSpy before resetting it."); } } if (args[0].ToLower().Trim() == "-silent" || args[0].ToLower().Trim('\\') == "s") { if (firstInstance) { silentstartup = true; } } else { for (int index = 0; index < args.Length; index++) { string s = args[index]; command += s + " "; } } } if (!firstInstance) { if (!String.IsNullOrEmpty(command)) { File.WriteAllText(AppDataPath + "external_command.txt", command); //ensures pickup by filesystemwatcher Thread.Sleep(1000); } Application.Exit(); return; } if (VlcHelper.VlcInstalled) VlcHelper.AddVlcToPath(); File.WriteAllText(AppDataPath + "external_command.txt", ""); // in case our https certificate ever expires or there is some other issue ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; WriterMutex = new Mutex(); Application.ThreadException += ApplicationThreadException; var mf = new MainForm(silentstartup, command); Application.Run(mf); WriterMutex.Close(); WriterMutex.Dispose(); } catch (Exception ex) { try { Log.Error("",ex);//MainForm.LogExceptionToFile(ex); } catch { } while (ex.InnerException != null) { try { Log.Error("",ex);//MainForm.LogExceptionToFile(ex); } catch { } } } }
public static void Main() { Mutex mutex = null; var shouldWait = true; try { bool createdNew; mutex = new Mutex(true, MUTEX_NAME, out createdNew); if (createdNew == false) { OutputMessage("updatechromium is already running."); return; } shouldWait = Exec(); } catch (Exception e) { OutputError(e); } finally { if (shouldWait) { while (Console.KeyAvailable) Console.ReadKey(); OutputMessage(""); OutputMessage("Press enter to exit"); Console.ReadLine(); } if (mutex != null) { try { mutex.ReleaseMutex(); } catch (Exception e1) { OutputError(e1); } try { mutex.Dispose(); } catch (Exception e1) { OutputError(e1); } } } }
public bool NegTest3() { bool retVal = true; int testInt = 0; TestLibrary.TestFramework.BeginScenario("NegTest3: Check ArgumentOutOfRangeException will be thrown if millisecondsTimeout is a negative number other than -1"); try { testInt = TestLibrary.Generator.GetInt32(); if (testInt > 0) { testInt = 0 - testInt; } if (testInt == -1) { testInt--; } m_Mutex = new Mutex(); m_Mutex.WaitOne(testInt); TestLibrary.TestFramework.LogError("105", "ArgumentOutOfRangeException is not thrown if millisecondsTimeout is a negative number other than -1"); TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] testInt = " + testInt); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] testInt = " + testInt); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; }
public bool PosTest1() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest1: Wait Infinite"); try { do { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(SleepLongTime)); thread.Start(); if (m_Mutex.WaitOne(Timeout.Infinite) != true) { TestLibrary.TestFramework.LogError("001", "Can not wait Infinite"); retVal = false; break; } m_Mutex.ReleaseMutex(); } while (false); // do } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; }
public bool NegTest1() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("NegTest1: AbandonedMutexException should be thrown if a thread exited without releasing a mutex"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(NeverReleaseMutex)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race m_Mutex.WaitOne(Timeout.Infinite); // AbandonedMutexException is not thrown on Windows 98 or Windows ME //if (Environment.OSVersion.Platform == PlatformID.Win32NT) //{ TestLibrary.TestFramework.LogError("101", "AbandonedMutexException is not thrown if a thread exited without releasing a mutex"); retVal = false; //} } catch (AbandonedMutexException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; }
public bool PosTest7() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest7: Wait infinite time when another thread is in nondefault managed context"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(CallContextBoundObjectMethod)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race if (true != m_Mutex.WaitOne(Timeout.Infinite)) { m_Mutex.ReleaseMutex(); TestLibrary.TestFramework.LogError("012", "WaitOne returns false when wait infinite time when another thread is in nondefault managed context"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("013", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; }
public bool PosTest3() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest3: Wait some finite time will quit for timeout"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(SignalMutex)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race if (false != m_Mutex.WaitOne(c_DEFAULT_SLEEP_TIME / 10)) { m_Mutex.ReleaseMutex(); TestLibrary.TestFramework.LogError("004", "WaitOne returns true when wait time out"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; }
public bool PosTest2() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest2: Wait some finite time"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(SignalMutex)); thread.Start(); m_Mutex.WaitOne(2 * c_DEFAULT_SLEEP_TIME); m_Mutex.ReleaseMutex(); } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; }
/// <summary> /// Set the live tile status /// </summary> /// <param name="fromSettings">indicate if called from seettings window, which means the user will get notifications</param> public static void SetLiveTile(bool fromSettings) { string isTileEnabled; bool tileSettingsExist = IsolatedStorageSettings.ApplicationSettings.TryGetValue<string>("EnableTile", out isTileEnabled); string taskName = "Waze Periodic Task"; Mutex mLiveTileStorageMutex = new Mutex(true,"LiveTileStorageMutex"); try { mLiveTileStorageMutex.WaitOne(); IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); if (!isf.DirectoryExists("LiveTile")) { isf.CreateDirectory("LiveTile"); } // Save the home name in selected language so the task can search for it later on. using (IsolatedStorageFileStream fsHomeName = isf.OpenFile("LiveTile\\HomeName", FileMode.Create,FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fsHomeName)) { sw.Write(LanguageResources.Instance.Translate("Home")); } } // Save the home name in selected language so the task can search for it later on. using (IsolatedStorageFileStream fsWorkName = isf.OpenFile("LiveTile\\WorkName", FileMode.Create, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fsWorkName)) { sw.Write(LanguageResources.Instance.Translate("Work")); sw.Flush(); } } // Save the refresh interval so the task can search for it later on. using (IsolatedStorageFileStream fsInterval = isf.OpenFile("LiveTile\\Interval",FileMode.Create,FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fsInterval)) { if (IsolatedStorageSettings.ApplicationSettings.Contains("TileRefreshInterval")) { sw.Write(IsolatedStorageSettings.ApplicationSettings["TileRefreshInterval"].ToString()); } else { sw.Write("10"); } sw.Flush(); } } } finally { mLiveTileStorageMutex.ReleaseMutex(); mLiveTileStorageMutex.Dispose(); } PeriodicTask periodicTask = new PeriodicTask(taskName); periodicTask.Description = "Waze Task to update Live Tile"; // Make the task alive for atnoher 14 days. If the user didn't run waze for 14 days, the task will auto delete by the system. periodicTask.ExpirationTime = System.DateTime.Now.AddDays(14); // If the agent is already registered with the system, remove it first if (ScheduledActionService.Find(periodicTask.Name) != null) { ScheduledActionService.Remove(taskName); } // Clear the current tile ShellTile currentTiles = ShellTile.ActiveTiles.First(); StandardTileData tilesUpdatedData = new StandardTileData { Title = "Waze", BackgroundImage = new Uri("waze_logo.png", UriKind.Relative), Count = 0, BackTitle = string.Empty, BackContent = string.Empty }; currentTiles.Update(tilesUpdatedData); // Place the call to Add in a try block in case the user has disabled agents, but selected to turn it on from the app: try { // If the user selected to turn it on, add the task: if(isTileEnabled != "No") { ScheduledActionService.Add(periodicTask); // Update the Tile for the first time within 5 seconds (Won't work for marketplace app): ScheduledActionService.LaunchForTest(taskName,TimeSpan.FromSeconds(5)); } } catch (InvalidOperationException exception) { if (exception.Message.Contains("BNS Error: The action is disabled")) { if (fromSettings) { MessageBox.Show(LanguageResources.Instance.Translate("Background agents for this application have been disabled by the user.")); } } if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added.")) { // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached. } } catch (SchedulerServiceException) { // No user action required. } }