回调中的异步方法

Async methods in callbacks

我想做的是创建一个后台任务,记录 Phone 的每次解锁,但我无法写入日志。

这就是我注册后台任务的方式:

public App()
    {
        this.InitializeComponent();
        this.Suspending += this.OnSuspending;

        backgroundTask = registerBackgroundTask();
    }

    private BackgroundTaskRegistration registerBackgroundTask()
    {
        // -----------------------------
        const string taskName = "BackgroundTask_Task";
        // -----------------------------


        IAsyncOperation<BackgroundAccessStatus> accessStatus = BackgroundExecutionManager.RequestAccessAsync();

        SystemTrigger systemTrigger = new SystemTrigger(SystemTriggerType.UserPresent, false);

        foreach( var cur in BackgroundTaskRegistration.AllTasks )
        {
            if( cur.Value.Name == taskName )
            {
                // The Task is already registered.
                return (BackgroundTaskRegistration)(cur.Value);
            }
        }

        BackgroundTaskBuilder builder = new BackgroundTaskBuilder();

        builder.Name = taskName;
        builder.TaskEntryPoint = typeof(BackgroundTask_Task.Task).FullName;
        builder.SetTrigger(systemTrigger);

        return builder.Register();

    }

然后我正在尝试这个:

public async void Run(IBackgroundTaskInstance taskInstance)
    {
        Debug.WriteLine("Test");
        Debug.WriteLine(DateTime.Now.ToString("g"));

        StorageFolder dataFolder = ApplicationData.Current.LocalFolder;
        StorageFile logFile = await dataFolder.CreateFileAsync("logFile.txt", CreationCollisionOption.OpenIfExists);

        IList<string> logLines = await FileIO.ReadLinesAsync(logFile);

        foreach( var s in logLines )
        {
            Debug.WriteLine(s);
        }

        logLines.Add(DateTime.Now.ToString("g"));
        if( logLines.Count > 5 )
        {
            logLines.RemoveAt(0);
        }

        await FileIO.AppendLinesAsync(logFile, logLines);

    }

但问题是它不会 read/write 来自 logFile.txt。 (有时是,但不是每次)。

我认为我不能只进行系统调用异步以在其中使用异步方法,这是有道理的。但是后来我尝试 运行 将它变成一个带有 ThreadPool.RunAsync 的异步 lamdbda,也没有成功。当你想在非异步的函数中调用异步方法时,你通常会做什么?

在这个blog entry中提到,异步工作需要封装在后台任务延迟

public async void Run(IBackgroundTaskInstance taskInstance)
{
    BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

    Debug.WriteLine("Test");
        Debug.WriteLine(DateTime.Now.ToString("g"));

        StorageFolder dataFolder = ApplicationData.Current.LocalFolder;
        StorageFile logFile = await dataFolder.CreateFileAsync("logFile.txt", CreationCollisionOption.OpenIfExists);

        IList<string> logLines = await FileIO.ReadLinesAsync(logFile);

        foreach( var s in logLines )
        {
            Debug.WriteLine(s);
        }

        logLines.Add(DateTime.Now.ToString("g"));
        if( logLines.Count > 5 )
        {
            logLines.RemoveAt(0);
        }

        await FileIO.AppendLinesAsync(logFile, logLines);

    _deferral.Complete(); 
}