2017-08-16 45 views
0

我有一个方法,我想在xamarin应用程序的后台调用我的应用程序。如何在Xamarin应用程序的背景中调用异步方法

我写了这样的事情

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

    } 
} 

我的方法是这样的:

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

    myType= await SomeMethod(); 

    return myType; 

} 

当我添加async我的方法是这样

protected async override void OnStart() 

我收到此错误

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

当我添加了异步lambda表达式这样,

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

我现在收到此错误

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>'. 

可能是什么问题,我怎样才能解决这个问题?

回答

1

假设myMethod返回一个Task,即:

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

然后就可以调用Device.StartTimerOnCreate这样的:

Device.StartTimer(new TimeSpan(0, 0, 1),() => 
{ 
    if (stopWatch.IsRunning && stopWatch.Elapsed.Minutes == 2) 
    { 
     myMethod().ContinueWith((Task t) => 
     { 
      stopWatch.Restart(); 
      return true; 
     }); 
    } 
    return true; 
});