gpt4 book ai didi

c# - BackgroundTask deferral.Complete

转载 作者:行者123 更新时间:2023-11-30 20:56:35 25 4
gpt4 key购买 nike

我的问题是,deferral.complete() 方法到底是做什么的,这个方法调用事件 task.Compledet,还是有办法调用一个我的类 BackgroundSyncerBackgroundTaskSyncer 的方法 ?????当我运行 Programm 时,我将从 BackgroundTaskSyncer 执行 Run 方法,但在其他类中什么都不做??

    namespace NotificationTask
{
public sealed class BackgroundTaskSyncer : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
deferral.Complete();
}
}
}
namespace Services
{

public static class BackgroundSync
{
private static async Task RegisterBackgroundTask()
{
try
{
BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
if (status == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity || status == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
{
bool isRegistered = BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name == "Notification task");
if (!isRegistered)
{
BackgroundTaskBuilder builder = new BackgroundTaskBuilder
{
Name = "Notification task",
TaskEntryPoint =
"NotificationTask.BackgroundTaskSyncer"
};
builder.SetTrigger(new TimeTrigger(15, false));
builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
BackgroundTaskRegistration task = builder.Register();
task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("The access has already been granted");
}
}
private static void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
{
ToTheBackGroundWork();
}

最佳答案

创建延迟是为了解决 async void 事件和方法的问题。例如,如果您在后台操作期间必须 await,则可以使用 async void Run 方法。但这样做的问题是运行时不知道您实际上还有更多工作要做。

因此,延迟是一个对象,您可以使用它来通知运行时“我现在真的完成了”。仅当您需要 await 时才需要延迟。

我有一个 blog post that goes into "asynchronous event handlers" and deferrals in more detail .

关于c# - BackgroundTask deferral.Complete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17451551/

25 4 0