本文整理汇总了C#中Windows.ApplicationModel.Background.BackgroundTaskDeferral.?.Complete方法的典型用法代码示例。如果您正苦于以下问题:C# BackgroundTaskDeferral.?.Complete方法的具体用法?C# BackgroundTaskDeferral.?.Complete怎么用?C# BackgroundTaskDeferral.?.Complete使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.ApplicationModel.Background.BackgroundTaskDeferral
的用法示例。
在下文中一共展示了BackgroundTaskDeferral.?.Complete方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
try
{
_resourceLoader = ResourceLoader.GetForViewIndependentUse();
}
catch (Exception ex)
{
// todo: do something
}
_serviceDeferral = taskInstance.GetDeferral();
// If cancelled, set deferal
// Mets le déféral si annulation
taskInstance.Canceled += (sender, reason) => _serviceDeferral?.Complete();
// Get the details of the event that trigered the service
// Obtient les détails de l'évenement qui à démarré le service
var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
// Check if it is service name set in VCD
// Regarde si c'est le nom du service qui est mis dans le VCD
if (triggerDetails?.Name == "PresidentsService")
{
_voiceCommandServiceConnection =
VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
// Set deferal when voice command is completed
// Mets le deferal quand la commande vocale est terminée
_voiceCommandServiceConnection.VoiceCommandCompleted += (sender, args) => _serviceDeferral?.Complete();
// Get voice command
// Obtient la commande vocale
var voicecommand = await _voiceCommandServiceConnection.GetVoiceCommandAsync();
switch (voicecommand.CommandName)
{
case "whichPresidentYear":
var year = voicecommand.Properties["year"][0];
await SendProgressMessageAsync(string.Format(GetString(Strings.LookingYear), year));
await SearchPresidentForYearAsync(year);
break;
case "showTerm":
var president = voicecommand.Properties["president"][0];
await SendProgressMessageAsync(string.Format(GetString(Strings.LookingTerms), president));
await SearchTermOfPresidentAsync(president);
break;
}
}
}
示例2: Run
/// <summary>
/// The Run method is the entry point of a background task.
/// </summary>
/// <param name="taskInstance"></param>
public async void Run(IBackgroundTaskInstance taskInstance)
{
try
{
// LOLLO Background tasks may take up max 40 MB. There is also a time limit I believe.
// We should keep it as stupid as possible,
// so we only add a line to the db without reading anything.
// Query BackgroundWorkCost
// Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
// of work in the background task and return immediately.
_deferral = taskInstance.GetDeferral();
await Task.Delay(5000).ConfigureAwait(false); // this picks up the last changes in case too many requests were triggered and the last were rejected.
// LOLLO TODO make sure it does not screw with the timeout.
_taskInstance = taskInstance;
_taskInstance.Canceled += OnCanceled;
_cts = new SafeCancellationTokenSource();
var cancToken = _cts.Token;
// LOLLO the following fails with an uncatchable exception "System.ArgumentException use of undefined keyword value 1 for event taskscheduled"
// only in the background task and only if called before GetDeferral and only if awaited
Logger.Add_TPL("BackgroundOneDriveUploader started", Logger.BackgroundLogFilename, Logger.Severity.Info, false);
//if (GetLocBackgroundTaskSemaphoreManager.TryOpenExisting())
// return; // the app is running, it will catch the background task running: do nothing
_taskInstance.Progress = 1;
// we don't need this but we leave it in case we change something and we want to check when the bkg task starts.
var briefcase = Briefcase.GetCreateInstance(true);
await briefcase.OpenAsync().ConfigureAwait(false);
if (briefcase.RuntimeData?.IsConnectionAvailable == true)
{
await briefcase.MetaBriefcase.SaveIntoOneDriveAsync(cancToken, taskInstance.InstanceId).ConfigureAwait(false);
}
}
catch (ObjectDisposedException) // comes from the cts
{
Logger.Add_TPL("ObjectDisposedException", Logger.BackgroundLogFilename, Logger.Severity.Info, false);
}
catch (OperationCanceledException) // comes from the cts
{
Logger.Add_TPL("OperationCanceledException", Logger.BackgroundLogFilename, Logger.Severity.Info, false);
}
catch (Exception ex)
{
await Logger.AddAsync(ex.ToString(), Logger.BackgroundLogFilename).ConfigureAwait(false);
}
finally
{
_cts?.Dispose();
_cts = null;
if (_taskInstance != null) _taskInstance.Canceled -= OnCanceled;
Logger.Add_TPL("BackgroundOneDriveUploader ended", Logger.BackgroundLogFilename, Logger.Severity.Info, false);
_deferral?.Complete();
}
}
示例3: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
Country selectedcountry;
// We need deferal
// On a besoin de deferal
_serviceDeferral = taskInstance.GetDeferral();
// If cancelled, set deferal
// Mets le déféral si annulation
taskInstance.Canceled += (sender, reason) => _serviceDeferral?.Complete();
// Get the details of the event that trigered the service
// Obtient les détails de l'évenement qui à démarré le service
var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
// Check if it is service name set in VCD
// Regarde si c'est le nom du service qui est mis dans le VCD
if (triggerDetails?.Name == "FlagoramaService")
{
_voiceCommandServiceConnection =
VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
// Set deferal when voice command is completed
// Mets le deferal quand la commande vocale est terminée
_voiceCommandServiceConnection.VoiceCommandCompleted += (sender, args) => _serviceDeferral?.Complete();
// Get voice command
// Obtient la commande vocale
var voicecommand = await _voiceCommandServiceConnection.GetVoiceCommandAsync();
switch (voicecommand.CommandName)
{
case "showFlagList":
// Show flag list
selectedcountry = await ShowFlagListAsync();
if (selectedcountry != null)
{
// If one flag is selected, ask confirmation
if (await PromptForConfirmationAsync(selectedcountry))
{
// Send success message with selected flag
await SendSuccessMessageAsync(selectedcountry);
}
}
break;
case "showFlag":
await SendErrorMessageAsync();
await Task.Delay(2000);
// Get country flags with selected name
var flags = Countries.List.Where(
d => d.Name.ToLower().Contains(voicecommand.Properties["flag"][0].ToLower())).ToList();
// If more than one, disambiguate
if (flags.Count() == 1)
selectedcountry = flags.First();
else
{
selectedcountry = await DisambiguateCountry(flags);
}
// Show progress message for 2 seconds, then show flag
await SendProgressMessageAsync(selectedcountry);
await Task.Delay(20000);
await SendSuccessMessageAsync(selectedcountry);
break;
}
}
}
示例4: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
serviceDeferral = taskInstance.GetDeferral();
taskInstance.Canceled += OnTaskCanceled;
var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
if (triggerDetails != null)
{
var config = new AIConfiguration("cb9693af-85ce-4fbf-844a-5563722fc27f",
"40048a5740a1455c9737342154e86946",
SupportedLanguage.English);
apiAi = new ApiAi(config);
apiAi.DataService.PersistSessionId();
try
{
voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
voiceServiceConnection.VoiceCommandCompleted += VoiceCommandCompleted;
var voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();
var recognizedText = voiceCommand.SpeechRecognitionResult?.Text;
switch (voiceCommand.CommandName)
{
case "type":
{
var aiResponse = await apiAi.TextRequestAsync(recognizedText);
await apiAi.LaunchAppInForegroundAsync(voiceServiceConnection, aiResponse);
}
break;
case "unknown":
{
if (!string.IsNullOrEmpty(recognizedText))
{
var aiResponse = await apiAi.TextRequestAsync(recognizedText);
if (aiResponse != null)
{
await apiAi.SendResponseToCortanaAsync(voiceServiceConnection, aiResponse);
}
}
}
break;
case "greetings":
{
var aiResponse = await apiAi.TextRequestAsync(recognizedText);
var repeatMessage = new VoiceCommandUserMessage
{
DisplayMessage = "Repeat please",
SpokenMessage = "Repeat please"
};
var processingMessage = new VoiceCommandUserMessage
{
DisplayMessage = aiResponse?.Result?.Fulfillment?.Speech ?? "Pizza",
SpokenMessage = ""
};
var resp = VoiceCommandResponse.CreateResponseForPrompt(processingMessage, repeatMessage);
await voiceServiceConnection.ReportSuccessAsync(resp);
break;
}
default:
if (!string.IsNullOrEmpty(recognizedText))
{
var aiResponse = await apiAi.TextRequestAsync(recognizedText);
if (aiResponse != null)
{
await apiAi.SendResponseToCortanaAsync(voiceServiceConnection, aiResponse);
}
}
else
{
await SendResponse("Can't recognize");
}
break;
}
}
catch(Exception e)
{
var message = e.ToString();
Debug.WriteLine(message);
}
finally
{
serviceDeferral?.Complete();
}
}
}