C# 如何在Xamarin应用程序的后台调用异步方法
我有一个方法,我想在xamarin应用程序我的应用程序的后台调用它 我写了这样的东西C# 如何在Xamarin应用程序的后台调用异步方法,c#,xamarin,lambda,xamarin.forms,C#,Xamarin,Lambda,Xamarin.forms,我有一个方法,我想在xamarin应用程序我的应用程序的后台调用它 我写了这样的东西 public partial class App : Application { private static Stopwatch stopWatch = new Stopwatch(); protected override void OnStart() { if (!stopWatch.IsRunning) { stopWatch.Sta
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();
}
});
}
}
protected async override void OnStart()
我的方法是这样的:
public async static Task <Mytype> myMethod()
{
MyType myType;
myType= await SomeMethod();
return myType;
}
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
if (stopWatch.IsRunning && stopWatch.Elapsed.Minutes == 2)
{
myMethod().ContinueWith((Task t) =>
{
stopWatch.Restart();
return true;
});
}
return true;
});
我收到这个错误
The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.
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>'.
当我像这样添加异步lambda表达式时
Device.StartTimer(new TimeSpan(0, 0, 1), async () =>
我现在收到了这个错误
The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.
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>'.
无法将异步lambda表达式转换为委托类型“Func”。异步lambda表达式可能返回void、Task或Task,它们都不能转换为“Func”。
问题可能是什么?如何解决此问题?假设
myMethod
返回任务,即:
async Task myMethod()
{
Debug.WriteLine("Processing something....");
await Task.Delay(1); // replace with what every you are processing....
}
然后您可以在OnCreate
中调用Device.StartTimer
,如下所示:
public async static Task <Mytype> myMethod()
{
MyType myType;
myType= await SomeMethod();
return myType;
}
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
if (stopWatch.IsRunning && stopWatch.Elapsed.Minutes == 2)
{
myMethod().ContinueWith((Task t) =>
{
stopWatch.Restart();
return true;
});
}
return true;
});
假设myMethod
返回任务,即:
async Task myMethod()
{
Debug.WriteLine("Processing something....");
await Task.Delay(1); // replace with what every you are processing....
}
然后您可以在OnCreate
中调用Device.StartTimer
,如下所示:
public async static Task <Mytype> myMethod()
{
MyType myType;
myType= await SomeMethod();
return myType;
}
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
if (stopWatch.IsRunning && stopWatch.Elapsed.Minutes == 2)
{
myMethod().ContinueWith((Task t) =>
{
stopWatch.Restart();
return true;
});
}
return true;
});