【发布时间】:2017-08-21 12:34:13
【问题描述】:
我使用 TPL 实现了一个简单的任务。它等待 10 秒执行并返回 true/false。
var checkCFOPTask = Task.Run(() => CheckCFOPExists());
checkCFOPTask.Wait(TimeSpan.FromSeconds(10));
if (checkCFOPTask.Result)
{
}
else
{
}
问题是我的代码卡在 if 语句中。
if (checkCFOPTask.Result)
每次我暂停调试器时,它仍然在上面的代码行中等待。这是第一次发生。理想情况下,它应该在 10 秒内返回真/假。
以下是函数定义-
CheckCFOExists:由任务执行。
private bool CheckCFOPExists()
{
bool found = false;
try
{
while (!found)
{
try
{
if (ieDriver.FindElement(By.Id("popup_message")).Text == "Não existem itens para realizar o rateio.")
{
ResetInvoiceSearchScreen();
break;
}
}
catch (Exception ex)
{
}
try
{
if (arrCFOPList.Contains(ieDriver.FindElement(By.Id("vendorNF.cfopOperCode")).GetAttribute("value")))
{
found = true;
}
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
}
return found;
}
ResetInvoiceSearchScreen:在上述函数内执行
private void ResetInvoiceSearchScreen()
{
try
{
ieDriver.FindElement(By.Id("popup_ok")).Click();
ieDriver.FindElement(By.Id("ltmCnpjCpf")).Clear();
ieDriver.FindElement(By.Id("notaFiscalNbr")).Clear();
ieDriver.FindElement(By.Id("inbNotaFiscalId")).Clear();
ieDriver.FindElement(By.Id("seriesFrmCd")).Clear();
}
catch (Exception ex)
{
}
}
是否还需要其他东西来确保函数正确超时?如果我可以提供更多详细信息,请告诉我。
编辑
我在 Visual Studio 的即时窗口中看到checkCFOPTask.Result 的以下消息-
Id = Cannot evaluate expression because the code of the current method is optimized., Status = Cannot evaluate expression because the code of the current method is optimized., Method = Cannot evaluate expression because the code of the current method is optimized., Result = Cannot evaluate expression because the code of the current method is optimized.
【问题讨论】:
-
如果没有在 10 秒内完成,它应该如何返回 true 或 false?
-
我认为您在寻找
Task.IsCompleted而不是Task.Result。
标签: c# .net task-parallel-library