gpt4 book ai didi

c# - 从任务中调用异常

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:12 24 4
gpt4 key购买 nike

我在库中有一个方法,它没有包含在 Task.Factory 语法中的任何控件,我想正确处理它抛出的异常并在 UI 中显示消息。考虑以下代码:

项目.WinForms:

public void button1_Click(object sender, EventArgs e)
{
try
{
library1.RunTask();
}
catch(Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}

项目核心:

public void RunTask()
{
Task.Factory.StartNew(() => {
try
{
throw new Exception("SAMPLE_EXCEPTION");
}
catch(Exception)
{
throw;
}
});
}

运行已编译的可执行文件时发生的情况是没有显示任何异常,UI 停留在类似进度的状态,但实际上,另一个线程中发生了异常。但是,在调试解决方案时,会抛出异常,从而中断代码的执行,如下所示:

enter image description here

最佳答案

您的RunTask 方法是异步的并且抛出异常。官方文档有一节关于 exceptions in async methods ,其中指出:

To catch the exception, await the task in a try block, and catch the exception in the associated catch block.

因此,让我们通过进行两项更改来做到这一点:

  1. 返回您在 RunTask() 中启动的 Task
  2. await 在事件处理程序的 try block 中执行该任务。

这里是 a simplified example你的场景。

// Use the async keyword, 
// so we can use await in the method body
public async void button1_Click(object sender, EventArgs e)
{
try
{
// await the completion of the task,
// without blocking the UI thread
await RunTask();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

// Change the signature to return a Task
public Task RunTask()
{
// Return the task that you started
return Task.Factory.StartNew(() =>
{
throw new Exception("SAMPLE_EXCEPTION");
});
}

// The following emulates your button click scenario
public event EventHandler<EventArgs> ButtonClickEvent;
public static void Main()
{
var p = new Program();
p.ButtonClickEvent += p.button1_Click;
p.ButtonClickEvent(p, new EventArgs());
}

为了更全面地解释正在发生的事情,我建议您参阅 Async/Await - Best Practices in Asynchronous Programming .

不过,有一项重要事项需要注意。我们从 button1_Click 事件处理程序返回 async void,即使它几乎总是 better to return async Task from an asynchronous method .但是,事件处理程序必须返回 void,因此我们不能使用 async Task,而必须使用 async void

关于c# - 从任务中调用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49837622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com