![](/img/trans.png)
[英]Is it possible to have async methods as callbacks to eventhandlers in c#?
[英]Async methods in callbacks
我要做的是做一個后台任務,記錄手機的每次解鎖,但是我無法使日志內容正常工作。
這就是我注冊后台任務的方式:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.