本文整理汇总了C#中Windows.ApplicationModel.Background.BackgroundTaskDeferral类的典型用法代码示例。如果您正苦于以下问题:C# BackgroundTaskDeferral类的具体用法?C# BackgroundTaskDeferral怎么用?C# BackgroundTaskDeferral使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BackgroundTaskDeferral类属于Windows.ApplicationModel.Background命名空间,在下文中一共展示了BackgroundTaskDeferral类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
//
// The Run method is the entry point of a background task.
//
public void Run(IBackgroundTaskInstance taskInstance)
{
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
// For performing asynchronous operations in the background task
BackgroundTaskDeferral asyncDeferral = taskInstance.GetDeferral();
//
// Query BackgroundWorkCost
// Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
// of work in the background task and return immediately.
//
var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
var settings = ApplicationData.Current.LocalSettings;
settings.Values["BackgroundWorkCost"] = cost.ToString();
//
// Associate a cancellation handler with the background task.
//
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
//
// Get the deferral object from the task instance, and take a reference to the taskInstance;
//
_deferral = taskInstance.GetDeferral();
_taskInstance = taskInstance;
_periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
asyncDeferral.Complete();
}
示例2: Run
/// <remarks>
/// If you start any asynchronous methods here, prevent the task
/// from closing prematurely by using BackgroundTaskDeferral as
/// described in http://aka.ms/backgroundtaskdeferral
/// </remarks>
public async void Run(IBackgroundTaskInstance taskInstance)
{
// This deferral should have an instance reference, if it doesn't... the GC will
// come some day, see that this method is not active anymore and the local variable
// should be removed. Which results in the application being closed.
_deferral = taskInstance.GetDeferral();
var restRouteHandler = new RestRouteHandler();
restRouteHandler.RegisterController<AsyncControllerSample>();
restRouteHandler.RegisterController<FromContentControllerSample>();
restRouteHandler.RegisterController<PerCallControllerSample>();
restRouteHandler.RegisterController<SimpleParameterControllerSample>();
restRouteHandler.RegisterController<SingletonControllerSample>();
restRouteHandler.RegisterController<ThrowExceptionControllerSample>();
restRouteHandler.RegisterController<WithResponseContentControllerSample>();
var configuration = new HttpServerConfiguration()
.ListenOnPort(8800)
.RegisterRoute("api", restRouteHandler)
.RegisterRoute(new StaticFileRouteHandler(@"Restup.DemoStaticFiles\Web"))
.EnableCors(); // allow cors requests on all origins
// .EnableCors(x => x.AddAllowedOrigin("http://specificserver:<listen-port>"));
var httpServer = new HttpServer(configuration);
_httpServer = httpServer;
await httpServer.StartServerAsync();
// Dont release deferral, otherwise app will stop
}
示例3: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
serviceDeferral = taskInstance.GetDeferral();
taskInstance.Canceled += OnTaskCanceled;
var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
if (triggerDetails == null)
{
serviceDeferral.Complete();
return;
}
try
{
voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;
var voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();
//Find the command name witch should match the VCD
if (voiceCommand.CommandName == "buildit_help")
{
var props = voiceCommand.Properties;
await CortanaHelpList();
}
await Task.Delay(1000);
await ShowProgressScreen();
}
catch
{
Debug.WriteLine("Unable to process voice command");
}
serviceDeferral.Complete();
}
示例4: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
// Create the deferral by requesting it from the task instance
serviceDeferral = taskInstance.GetDeferral();
AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
if (triggerDetails != null && triggerDetails.Name.Equals("IMCommandVoice"))
{
voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();
// Perform the appropriate command depending on the operation defined in VCD
switch (voiceCommand.CommandName)
{
case "oldback":
VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();
userMessage.DisplayMessage = "The current temperature is 23 degrees";
userMessage.SpokenMessage = "The current temperature is 23 degrees";
VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage, null);
await voiceServiceConnection.ReportSuccessAsync(response);
break;
default:
break;
}
}
// Once the asynchronous method(s) are done, close the deferral
serviceDeferral.Complete();
}
示例5: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
try {
var triggerDetail = (AppServiceTriggerDetails) taskInstance.TriggerDetails;
_deferral = taskInstance.GetDeferral();
Hub.Instance.ForegroundConnection = triggerDetail.AppServiceConnection;
Hub.Instance.ForegroundTask = this;
taskInstance.Canceled += (s, e) => Close();
triggerDetail.AppServiceConnection.ServiceClosed += (s, e) => Close();
}
catch (System.Exception e)
{
if (Hub.Instance.IsAppInsightsEnabled)
{
Hub.Instance.RTCStatsManager.TrackException(e);
}
if (_deferral != null)
{
_deferral.Complete();
}
throw e;
}
}
示例6: Run
/// <summary>
/// Hệ thống gọi đến hàm này khi association backgroundtask được bật
/// </summary>
/// <param name="taskInstance"> hệ thống tự tạo và truyền vào đây</param>
public async void Run(IBackgroundTaskInstance taskInstance)
{
//System.Diagnostics.Debug.WriteLine("background run");
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(BackgroundTaskCanceled);
taskInstance.Task.Completed += new BackgroundTaskCompletedEventHandler(BackgroundTaskCompleted);
_backgroundstarted.Set();//
_deferral = taskInstance.GetDeferral();
//Playlist = new BackgroundPlaylist();
_smtc = initSMTC();
this._foregroundState = this.initForegroundState();
BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayer_CurrentStateChanged;
//Playlist = await BackgroundPlaylist.LoadBackgroundPlaylist("playlist.xml");
Playlist = new BackgroundPlaylist();
Playlist.ListPathsource = await BackgroundPlaylist.LoadCurrentPlaylist(Constant.CurrentPlaylist);
if (_foregroundState != eForegroundState.Suspended)
{
ValueSet message = new ValueSet();
message.Add(Constant.BackgroundTaskStarted, "");
BackgroundMediaPlayer.SendMessageToForeground(message);
}
Playlist.TrackChanged += Playlist_TrackChanged;
BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
BackgroundMediaPlayer.Current.MediaEnded +=Current_MediaEnded;
ApplicationSettingHelper.SaveSettingsValue(Constant.BackgroundTaskState, Constant.BackgroundTaskRunning);
isbackgroundtaskrunning = true;
_loopState = eLoopState.None;
}
示例7: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
// Ensure our background task remains running
taskDeferral = taskInstance.GetDeferral();
// Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage
mutex = new Mutex(false, mutexId);
// Initialize ConnectTheDots Settings
localSettings.ServicebusNamespace = "iotbuildlab-ns";
localSettings.EventHubName = "ehdevices";
localSettings.KeyName = "D1";
localSettings.Key = "iQFNbyWTYRBwypMtPmpfJVz+NBgR32YHrQC0ZSvId20=";
localSettings.DisplayName = GetHostName();
localSettings.Organization = "IoT Build Lab";
localSettings.Location = "USA";
SaveSettings();
// Initialize WeatherShield
await shield.BeginAsync();
// Create a timer-initiated ThreadPool task to read data from I2C
i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds));
// Start the server
server = new HttpServer(port);
var asyncAction = ThreadPool.RunAsync((w) => { server.StartServer(shield, weatherData); });
// Task cancellation handler, release our deferral there
taskInstance.Canceled += OnCanceled;
// Create a timer-initiated ThreadPool task to renew SAS token regularly
SasTokenRenewTimer = ThreadPoolTimer.CreatePeriodicTimer(RenewSasToken, TimeSpan.FromMinutes(15));
}
示例8: Run
public async void Run(IBackgroundTaskInstance taskInstance) {
try {
// Ensure our background task remains running
taskDeferral = taskInstance.GetDeferral();
// Initialize cloud connection
azureConnector = new AzureConnector();
await azureConnector.InitAsync();
// Initialize WeatherShield
await shield.BeginAsync();
// Create a timer-initiated ThreadPool task to read data from I2C
ThreadPoolTimer.CreatePeriodicTimer(async (source) => {
await readAndSendWeatherRecord();
}, TimeSpan.FromSeconds(weatherShieldReadInterval));
// Task cancellation handler, release our deferral there
taskInstance.Canceled += OnCanceled;
} catch(Exception ex) {
await LogExceptionAsync(nameof(Run), ex);
if(Debugger.IsAttached) {
Debugger.Break();
}
// If it goes to shit here, rethrow which will terminate the process - but at least we have it logged!
throw;
}
}
示例9: Run
public async void Run( IBackgroundTaskInstance taskInstance )
{
Deferral = taskInstance.GetDeferral();
XParameter[] Params = SavedChannels.Parameters( "channel" );
if ( Params.Length == 0 )
{
Deferral.Complete();
return;
}
// Associate a cancellation handler with the background task.
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler( OnCanceled );
foreach ( XParameter Param in Params )
{
CurrentTask = new XParameter( DateTime.Now.ToFileTime() + "" );
CurrentTask.SetValue( new XKey[] {
new XKey( "name", taskInstance.Task.Name )
, new XKey( "start", true )
, new XKey( "end", false )
} );
PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
if ( channel.Uri != Param.GetValue( "uri" ) )
{
await RenewChannel( Param.GetValue( "provider" ), Param.Id, Uri.EscapeDataString( channel.Uri ) );
}
}
Deferral.Complete();
}
示例10: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
// Ensure our background task remains running
taskDeferral = taskInstance.GetDeferral();
// Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage
mutex = new Mutex(false, mutexId);
// Initialize ConnectTheDots Settings
localSettings.ServicebusNamespace = "windowactuator-ns";
localSettings.EventHubName = "ehdevices";
localSettings.KeyName = "D1";
localSettings.Key = "1uMOwjURpgGX9l5JqnYeatBkIRoLzP7qH8YGFUeAIrU=";
localSettings.DisplayName = GetHostName();
localSettings.Organization = "Ulster University";
localSettings.Location = "North Europe";
SaveSettings();
// Initialize WeatherShield
await shield.BeginAsync();
// Create a timer-initiated ThreadPool task to read data from I2C
i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds));
// Start the server
server = new HttpServer(port);
var asyncAction = ThreadPool.RunAsync((w) => { server.StartServer(shield, weatherData); });
// Task cancellation handler, release our deferral there
taskInstance.Canceled += OnCanceled;
// Create a timer-initiated ThreadPool task to renew SAS token regularly
SasTokenRenewTimer = ThreadPoolTimer.CreatePeriodicTimer(RenewSasToken, TimeSpan.FromMinutes(15));
}
示例11: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
Init();
temperatureTimer = ThreadPoolTimer.CreatePeriodicTimer(temperatureTimer_Tick, TimeSpan.FromMinutes(5));
thermostatStatusTimer = ThreadPoolTimer.CreatePeriodicTimer(thermostatStatusTimer_Tick, TimeSpan.FromMilliseconds(500));
}
示例12: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
deferral = taskInstance.GetDeferral();
InitGPIO();
GetBusArrivalData();
}
示例13: Run
/// <summary>
/// Entry point for the background task.
/// </summary>
public async void Run(IBackgroundTaskInstance taskInstance)
{
var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
if (null != triggerDetails && triggerDetails.Name == "LightControllerVoiceCommandService")
{
_deferral = taskInstance.GetDeferral();
taskInstance.Canceled += (s, e) => _deferral.Complete();
if (true != await InitializeAsync(triggerDetails))
{
return;
}
// These command phrases are coded in the VoiceCommands.xml file.
switch (_voiceCommand.CommandName)
{
case "changeLightsState": await ChangeLightStateAsync(); break;
case "changeLightsColor": await SelectColorAsync(); break;
case "changeLightStateByName": await ChangeSpecificLightStateAsync(); break;
default: await _voiceServiceConnection.RequestAppLaunchAsync(
CreateCortanaResponse("Launching HueLightController")); break;
}
// keep alive for 1 second to ensure all HTTP requests sent.
await Task.Delay(1000);
_deferral.Complete();
}
}
示例14: Run
/// <summary>
/// Background task entry point.
/// </summary>
/// <param name="taskInstance"></param>
public void Run(IBackgroundTaskInstance taskInstance)
{
Accelerometer = Accelerometer.GetDefault();
if (null != Accelerometer)
{
SampleCount = 0;
// Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
uint minReportIntervalMsecs = Accelerometer.MinimumReportInterval;
Accelerometer.ReportInterval = minReportIntervalMsecs > 16 ? minReportIntervalMsecs : 16;
// Subscribe to accelerometer ReadingChanged events.
Accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
// Take a deferral that is released when the task is completed.
Deferral = taskInstance.GetDeferral();
// Get notified when the task is canceled.
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
// Store a setting so that the app knows that the task is running.
ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = true;
}
}
示例15: Run
/// <summary>
/// Performs the work of a background task. The system calls this method when the associated
/// background task has been triggered.
/// </summary>
/// <param name="taskInstance">
/// An interface to an instance of the background task. The system creates this instance when the
/// task has been triggered to run.
/// </param>
public void Run(IBackgroundTaskInstance taskInstance)
{
Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting");
this.systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
this.systemMediaTransportControl.IsEnabled = true;
this.systemMediaTransportControl.IsPauseEnabled = true;
this.systemMediaTransportControl.IsPlayEnabled = true;
this.systemMediaTransportControl.IsNextEnabled = true;
this.systemMediaTransportControl.IsPreviousEnabled = true;
// Wire up system media control events
this.systemMediaTransportControl.ButtonPressed += this.OnSystemMediaTransportControlButtonPressed;
this.systemMediaTransportControl.PropertyChanged += this.OnSystemMediaTransportControlPropertyChanged;
// Wire up background task events
taskInstance.Canceled += this.OnTaskCanceled;
taskInstance.Task.Completed += this.OnTaskcompleted;
// Initialize message channel
BackgroundMediaPlayer.MessageReceivedFromForeground += this.OnMessageReceivedFromForeground;
// Notify foreground that we have started playing
BackgroundMediaPlayer.SendMessageToForeground(new ValueSet() { { "BackgroundTaskStarted", "" } });
this.backgroundTaskStarted.Set();
this.backgroundTaskRunning = true;
this.deferral = taskInstance.GetDeferral();
}