本文整理汇总了C#中IBackgroundTaskInstance.GetDeferral方法的典型用法代码示例。如果您正苦于以下问题:C# IBackgroundTaskInstance.GetDeferral方法的具体用法?C# IBackgroundTaskInstance.GetDeferral怎么用?C# IBackgroundTaskInstance.GetDeferral使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IBackgroundTaskInstance
的用法示例。
在下文中一共展示了IBackgroundTaskInstance.GetDeferral方法的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
/// <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();
}
示例3: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
AddQuestionsResult result = null;
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
#if DEBUG
InvokeSimpleToast("Hello from " + taskInstance.Task.Name);
#endif
try
{
result = await FeedManager.QueryWebsitesAsync();
#if DEBUG
InvokeSimpleToast(String.Format(
"There are {0} new questions and {1} updated questions.",
result.AddedQuestions,
result.UpdatedQuestions));
#endif
}
catch (Exception ex)
{
Debug.WriteLine(ex);
#if DEBUG
InvokeSimpleToast(ex.Message);
#endif
}
deferral.Complete();
}
示例4: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
//通知
ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
bool Update = true;
if (container.Values["UpdateCT"]!=null)
{
Update = (bool)container.Values["UpdateCT"];
}
else
{
container.Values["UpdateCT"] = true;
}
if (Update)
{
var deferral = taskInstance.GetDeferral();
await GetLatestNews();
deferral.Complete();
}
else
{
var updater = TileUpdateManager.CreateTileUpdaterForApplication();
updater.Clear();
}
}
示例5: 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();
}
示例6: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
var backgroundTaskDeferral = taskInstance.GetDeferral();
try { UpdateTile(); }
catch (Exception ex) { Debug.WriteLine(ex); }
finally { backgroundTaskDeferral.Complete(); }
}
示例7: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
taskInstance.Canceled += OnCanceled;
var defferal = taskInstance.GetDeferral();
TileHelper.UpdateTile(HomeSensorHelper.GetSensorData());
defferal.Complete();
}
示例8: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
var defferal = taskInstance.GetDeferral();
var taskHelper = new TaskHelper();
var signalingTask = taskHelper.GetTask(nameof(SignalingTask));
var connOwner = new ConnectionOwner
{
OwnerId = signalingTask.TaskId.ToString()
};
Hub.Instance.SignalingSocketService.ConnectToSignalingServer(connOwner);
Hub.Instance.SignalingClient.Register(new Registration
{
Name = RegistrationSettings.Name,
UserId = RegistrationSettings.UserId,
Domain = RegistrationSettings.Domain,
PushNotificationChannelURI = RegistrationSettings.PushNotificationChannelURI
});
defferal.Complete();
}
示例9: 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));
}
示例10: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
// Get the background task details
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
string taskName = taskInstance.Task.Name;
Debug.WriteLine("Background " + taskName + " starting...");
taskInstance.Canceled += TaskInstanceCanceled;
// Store the content received from the notification so it can be retrieved from the UI.
RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
container.Values["RawMessage"] = notification.Content.ToString();
//SendToastNotification(notification.Content);
Debug.WriteLine("Background " + taskName + " completed!");
_deferral.Complete();
}
示例11: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
System.Diagnostics.Debug.WriteLine("WE are @ Background");
_deferral = taskInstance.GetDeferral();
_taskInstance = taskInstance;
_taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
GattCharacteristicNotificationTriggerDetails details = (GattCharacteristicNotificationTriggerDetails)taskInstance.TriggerDetails;
//get the characteristics data and get heartbeat value out from it
byte[] ReceivedData = new byte[details.Value.Length];
DataReader.FromBuffer(details.Value).ReadBytes(ReceivedData);
HeartbeatMeasurement tmpMeasurement = HeartbeatMeasurement.GetHeartbeatMeasurementFromData(ReceivedData);
System.Diagnostics.Debug.WriteLine("Background heartbeast values: " + tmpMeasurement.HeartbeatValue);
// send heartbeat values via progress callback
_taskInstance.Progress = tmpMeasurement.HeartbeatValue;
//update the value to the Tile
LiveTile.UpdateSecondaryTile("" + tmpMeasurement.HeartbeatValue);
//Check if we are within the limits, and alert by starting the app if we are not
alertType alert = await checkHeartbeatLevels(tmpMeasurement.HeartbeatValue);
_deferral.Complete();
}
示例12: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
DataService ds = new DataService();
var quote = await ds.GetQuoteOfTheDayAsync();
//Create the Large Tile
var largeTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText09);
largeTile.GetElementsByTagName("text")[0].InnerText = quote.Author;
largeTile.GetElementsByTagName("text")[1].InnerText = quote.Content;
//Create a Small Tile
var smallTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareText04);
smallTile.GetElementsByTagName("text")[0].InnerText = quote.Content;
//Merge the two updates into one <visual> XML node
var newNode = largeTile.ImportNode(smallTile.GetElementsByTagName("binding").Item(0), true);
largeTile.GetElementsByTagName("visual").Item(0).AppendChild(newNode);
TileNotification notification = new TileNotification(largeTile);
TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
deferral.Complete();
}
示例13: 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;
}
示例14: Run
//TemperatureSensors tempSensors;
public void Run(IBackgroundTaskInstance taskInstance)
{
//if (!_started)
//{
// tempSensors = new TemperatureSensors();
// tempSensors.InitSensors();
// _started = true;
//}
// Associate a cancellation handler with the background task.
taskInstance.Canceled += TaskInstance_Canceled;
// Get the deferral object from the task instance
serviceDeferral = taskInstance.GetDeferral();
var appService = taskInstance.TriggerDetails as AppServiceTriggerDetails;
if (appService != null && appService.Name == "App2AppComService")
{
appServiceConnection = appService.AppServiceConnection;
appServiceConnection.RequestReceived += AppServiceConnection_RequestReceived; ;
}
// just run init, maybe don't need the above...
Initialize();
}
示例15: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
var deferal = taskInstance.GetDeferral();
if (taskInstance.TriggerDetails is RawNotification)
{
var details = taskInstance.TriggerDetails as RawNotification;
var arguments = details.Content.Split(':');
if (arguments.Count() > 0)
{
switch (arguments[0])
{
case "new_items":
if (arguments.Count() > 1)
{
XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
badgeElement.SetAttribute("value", arguments[1]);
BadgeNotification badge = new BadgeNotification(badgeXml);
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
}
break;
}
}
}
deferal.Complete();
}