user3841581 user3841581 - 10 months ago 33
C# Question

How to call an Asynchronous Method in the background of a Xamarin application

I have a method which I would like to call in the background of xamarin application my application.

I wrote something like this

public partial class App : Application
{
private static Stopwatch stopWatch = new Stopwatch();

protected override void OnStart()
{
if (!stopWatch.IsRunning)
{
stopWatch.Start();
}
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
if (stopWatch.IsRunning && stopWatch.Elapsed.Minutes== 2)
{
await myMethod() //This is the method which return a threat I would like to call
stopWatch.Restart();
}
});

}
}


My Method is something like this:

public async static Task <Mytype> myMethod()
{
MyType myType;

myType= await SomeMethod();

return myType;

}


When I add
async
to my the method like this

protected async override void OnStart()


I receive this error

The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.


When I add the asynchronous lambda expression like this,

Device.StartTimer(new TimeSpan(0, 0, 1), async () =>


I now received this error

Cannot convert async lambda expression to delegate type 'Func<bool>'. An async lambda expression may return void, Task or Task<T>, none of which are convertible to 'Func<bool>'.


What could be the problem and how can I fix this?

Answer Source

Assuming myMethod is returning a Task, i.e.:

async Task myMethod()
{
    Debug.WriteLine("Processing something....");
    await Task.Delay(1); // replace with what every you are processing....
}

Then you can call Device.StartTimer in the OnCreate like this:

Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
    if (stopWatch.IsRunning && stopWatch.Elapsed.Minutes == 2)
    {
        myMethod().ContinueWith((Task t) =>
        {
            stopWatch.Restart();
            return true;
        });
    }
    return true;
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download