2017-08-16 44 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; 
});