回调中的异步方法

时间:2015-06-21 20:57:57

标签: c# asynchronous windows-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);

    }

但问题是它不会从logFile.txt读/写。 (有时它确实但不是每次都这样做。)

我认为我不能只是使系统调用async来使用async方法,这是有意义的。但后来我尝试用ThreadPool.RunAsync将它运行到异步lamdbda中,也没有成功。当你想在非同步函数中调用异步方法时,你通常会做什么?

1 个答案:

答案 0 :(得分:1)

正如本blog entr中所述,异步工作需要封装在后台任务延迟中

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(); 
}