gpt4 book ai didi

c# - STA 线程异常传播

转载 作者:行者123 更新时间:2023-11-30 15:44:44 26 4
gpt4 key购买 nike

我有一个必须作为 STA 运行的函数,我想将它的异常传播到调用线程。在这里:

public void ExceptionBePropagatedThroughHere()
{
Thread thread = new Thread(TheSTAThread);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}

public void MainFunction()
{
try
{
ExceptionBePropagatedThroughHere();
}
catch(Exception e)
{
//will not hit here
}
}

将 STA 属性放在“MainFunction”上不是此处的选项。我注意到如果我使用的是 Task,try catch on task join 会将异常传播到调用线程,但是我不能将任务指定为 STA。

问题是如何将作为 STA 运行的异常传播到上述示例中的“MainFunction”?

提前致谢。

最佳答案

我听从了 Hans 的建议,解决方案如下所示,不需要触发任何事件。

private Exception _exception;
public void ExceptionBePropagatedThroughHere()
{
Thread thread = new Thread(TheSTAThread);Thread thread = new Thread(TheSTAThread);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
if(_exception != null)
throw new Exception("STA thread failed", _exception);
}

private void TheSTAThread()
{
try
{
//do the stuff
}
catch (Exception ex)
{
_exception = ex;
}
}
public void MainFunction()
{
try
{
ExceptionBePropagatedThroughHere();
}
catch(Exception e)
{
//will not hit here
}
}

关于c# - STA 线程异常传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5862655/

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