【发布时间】:2017-08-01 21:28:32
【问题描述】:
所以我明白为什么从异步返回 void 通常没有意义,但我遇到了一种情况,我认为它完全有效。考虑以下人为设计的示例:
protected override void OnLoad(EventArgs e)
{
if (CustomTask == null)
// Do not await anything, let OnLoad return.
PrimeCustomTask();
}
private TaskCompletionSource<int> CustomTask;
// I DO NOT care about the return value from this. So why is void bad?
private async void PrimeCustomTask()
{
CustomTask = new TaskCompletionSource<int>();
int result = 0;
try
{
// Wait for button click to set the value, but do not block the UI.
result = await CustomTask.Task;
}
catch
{
// Handle exceptions
}
CustomTask = null;
// Show the value
MessageBox.Show(result.ToString());
}
private void button1_Click(object sender, EventArgs e)
{
if (CustomTask != null)
CustomTask.SetResult(500);
}
我意识到这是一个不寻常的例子,但我试图让它变得简单和通用。有人可以向我解释为什么这是可怕的代码,以及如何修改它以正确遵循约定?
感谢您的帮助。
【问题讨论】:
-
@Nkosi 我明白为什么这是一种不好的做法,但为什么我的代码特别是这些坏做法的症状?如果不使用 void async,我还能怎么做?
-
@AnotherProgrammer 这似乎是XY problem。你想要达到的最终目标是什么?这个例子不清楚。
-
@AnotherProgrammer 我建议提供问题的minimal reproducible example 以及尝试了哪些解决方案,以便更好地理解问题并提供可行的解决方案。
-
@AnotherProgrammer: 不,
async void异常不能被Main捕获。而BackgroundWorker则没有同样的问题(虽然还有其他问题)。
标签: c# async-await