回调中的异步方法
本文关键字:异步方法 回调 | 更新日期: 2023-09-27 17:57:30
我想做的是做一个后台任务,记录手机的每次解锁,但我无法写入日志。
这就是我注册后台任务的方式:
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来使用其中的异步方法,这是有意义的。但后来我尝试用ThreadPool.RunAsync
将它运行到异步lamdbda中,但也没有成功。当你想在非异步函数中调用异步方法时,你通常会怎么做?
如本文所述,异步工作需要封装在后台任务延迟中
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();
}