最简单的解决将是
public override async SomeReturnTypeItem LoginAsync()
{
#if __MOBILE__
throw new NotSupportedException("Windows authentication is not supported in mobile version");
#else
//some code using await
#endif
}
但是这可能不完全是你想要的行为,因为如果__MOBILE__
是定义,该方法将返回故障Task
而不是立即投掷。这种差异有时会证明非常大,大多数情况下,如果您将Task
存储起来供以后使用,而不是立即等待(例如,如果要启动多个任务并让它们同时运行)。
为了解决这个问题,你应该把在方法的异常抛出代码和异步执行的另一个:
public override SomeReturnTypeItem LoginAsync()
{
#if __MOBILE__
throw new NotSupportedException("Windows authentication is not supported in mobile version");
#else
return LoginAsyncImpl();
#endif
}
private async SomeReturnTypeItem LoginAsync()
{
//some code using await
}
当然,如果你不使用await
可言,你只是不应该首先将您的方法标记为async
!
public override omeReturnTypeItem LoginAsync()
{
#if __MOBILE__
throw new NotSupportedException("Windows authentication is not supported in mobile version");
#else
//some code not using await
#endif
}
请注意,非异步代码仍然可以返回Task
。例如,如果您实现了一个接口或基类,这些接口或基类使一些方法返回任务,以便实现可以真正异步,但您的具体实现恰好是同步的,那么这很有用。
public override Task SomeMethodAsync()
{
// do some synchronous stuff
return Task.FromResutl(true);
}
你期望什么?如果设置了__MOBILE__,那么代码*是不可访问的 - 一个异常和它不会执行后的任何代码。如果您不想要警告,请删除代码或使用'#else'指令 –
如果您收到警告“方法缺乏等待操作符”,则根本不应该有'async'关键字,它适用于两个版本。 –
我是否安全地假设“某些代码”包含“await”? –