BeginBackgroundTask in Monotouch

2019-09-07 06:44发布

问题:

I need to do some processing after the application enters in the background so I added this code to my app:

public override void DidEnterBackground (UIApplication application)
{
    int taskid = 0;
    taskid = application.BeginBackgroundTask(() => {
        if(taskid != 0)
        {
            System.IO.File.WriteAllText(System.IO.Path.Combine(AppState.Current.User.Path, "blah"), "test");
            application.EndBackgroundTask(taskid);
            taskid = 0;
        }
    });
}

Then I monitored the filesystem (the emulator app) and the file never got written to the destination. Is there any reason why this is happening? Am I missing something?

回答1:

The parameter of BeginBackgroundTask method is the expiration handler. It will be executed right before your background time expires. That is where you should only end the task and nothing else.

It is after the BeginBackgroundTask call where your background time starts.

Apple documentation.

Multitasking on iOS with MonoTouch.