这就是我所拥有的。代码还有更多内容,但我只是输入了此片段以缩小问题范围。
public async Task GetCards(CancellationTokenSource cts)
{
try
{
while (true)
{
await CheckCardAvailability(cts);
}
}
catch (TaskCanceledException)
{
cts.Dispose();
}
}
private async Task CheckCardAvailability(CancellationTokenSource cts)
{
if (Counts.selectedCardCount == 0)
{
CardCountZeroMessages();
SetMessageView(false);
await Task.Delay(500, cts.Token);
return;
}
if (XYX == 0)
{
// other code
await Task.Delay(500, cts.Token);
return;
}
}
我在这里只有一个简单的返回,但是由于返回类型为Task,我应该做些不同的事情吗?请注意,我添加了返回值,因为我有许多if条件,并且我不想做很多if if if ..
答案 0 :(得分:2)
如@PanagiotisKanavos所述,您可以考虑将代码更改为:
public async Task GetCards(CancellationTokenSource cts)
{
try
{
while (true)
{
CheckCardAvailability(cts);
await Task.Delay(500, cts.Token); // or something with a timer
}
}
catch (TaskCanceledException)
{
cts.Dispose();
}
}
private /*async Task*/void CheckCardAvailability(CancellationTokenSource cts)
{
if (Counts.selectedCardCount == 0)
{
CardCountZeroMessages();
SetMessageView(false);
// await Task.Delay moved outside
}
if (XYX == 0)
{
// other code
// await Task.Delay moved outside
}
}