最簡單的解決將是
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」? –