简体   繁体   English

回调中的异步方法

[英]Async methods in callbacks

What I'm trying to do is make a background task that logs each unlock of the Phone but I can't get the writing to the log to work. 我要做的是做一个后台任务,记录手机的每次解锁,但是我无法使日志内容正常工作。

This is what how I'm registering a background Task: 这就是我注册后台任务的方式:

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

    }

And then im trying this: 然后我尝试这个:

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

    }

But the problem is it will not read/write from logFile.txt. 但是问题是它不会从logFile.txt中读取/写入。 (Sometimes it did but not everytime). (有时会,但并非每次都如此)。

I thought that I can't just make a system call async to use async methods in there which would make sense. 我以为我不能仅仅让系统调用async在其中使用异步方法就可以了。 But then I tried to run it into a async lamdbda with ThreadPool.RunAsync , no success either. 但是后来我尝试使用ThreadPool.RunAsync将其运行到异步lamdbda中,也没有成功。 What do you generally do when you want to call async methods in functions that are not async? 当您要在非异步函数中调用异步方法时,通常会做什么?

As mentioned in this blog entr y, the asynchronous work needs to be encapsulated in a background task deferral 如本博客文章所述,异步工作需要封装在后台任务延迟中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM