我有嘗試從網絡服務信息類幾聲:停止方法執行
public TResult Try(Func<TResult> func, int maxRetries)
{
TResult returnValue = default(TResult);
int numTries = 0;
bool succeeded = false;
while (numTries < maxRetries)
{
try
{
returnValue = func();
succeeded = true;
}
catch (Exception ex)
{
Log(ex,numTries);
}
finally
{
numTries++;
}
if (succeeded)
{
return returnValue;
}
else
{
if (numTries == maxRetries)
{
//ask user what to do
}
}
}
現在,經過「如果(numTries == maxRetries)」用戶將能夠如果他想繼續選擇試圖從Web服務獲取數據或取消。 我想在用戶取消時纔打開新窗體,並停止執行調用上述方法的方法。我不能只返回空或新的對象,因爲運行這個反彈的方法將繼續工作,並且在很多情況下會導致問題。
所以基本上,這看起來是這樣的:
someValue = retry.Try(() => webService.method(),maxRetries));
//if user canceled after app wasn't able to get data stop execution as already another form is opened
我當然可以檢查的,如果返回值爲空,如:
someValue = retry.Try(()=>webService.method(),maxRetries));
if (someValue == null)
return;
但是,這將意味着很多變化的代碼和我想避免它,如果我可以從Try方法做到最好。