gpt4 book ai didi

c# - 我需要一些在 C# 中使用线程的帮助

转载 作者:行者123 更新时间:2023-11-30 19:51:28 25 4
gpt4 key购买 nike

我正在用 C# 开发一个软件,它通过 Wrapper 使用 C++ .dll 文件中的静态函数。

问题是其中一些函数速度慢且不稳定,因此为了解决这个问题,我创建了一个线程来执行它们。然而,当我从主线程中止该线程时,程序不允许我再次使用这些函数,即使我每次调用函数时都定义了线程的新实例。

有什么办法可以解决这个问题吗?

提前致谢。

PS:这是我程序中的一些代码:

public partial class MainForm : Form, IMultiLanguage
{
//...

//This method is subscribed to the event of pressing the 'Abort' button
private void StopCurrentAnalisis()
{
try
{
this.analisisManagerController.AnalisisThread.Abort();
}
catch (Exception e){ }
finally
{
MessageBox.Show("Analisis has been cancelled by user", "Analisis Interrupted", MessageBoxButtons.OK, MessageBoxIcon.Stop);
CerrarNowLoadingForm();
}
}

//..
}

public class AnalisisManager: IAnalisisManagerController
{
//..
private Thread analisisThread;
public Thread AnalisisThread{get{return this.analisisThread;}}


public void MakePadrobAnalisis(TipoAnalisis tipoAnalisis,
Dictionary<string, Dictionary<int, double>> parametros)
{
object[] arregloParams = new object[]{tipoAnalisis,parametros};
analisisThread = new Thread(new ParameterizedThreadStart(MakeAnalisisInOtherThread));
analisisThread.Start(arregloParams);
}

private void MakeAnalisisInOtherThread(object o)
{
object[] arregloParams = o as object[];
TipoAnalisis tipoAnalisis = (TipoAnalisis) arregloParams[0];
Dictionary<string, Dictionary<int, double>> parametros = arregloParams[1] as Dictionary<string, Dictionary<int, double>>;

//This launches an event telling the GUI the unstable analisis has started.
//The method that makes the 'Abort' button to appear on the GUI is subscribed to this event
StartAnalisis();

//The Thread executes DLL functions according to tipoAnalisis, for example:
case InvKinematicsMinTorque:
{
WrapperPadirob.InverseKinematicsMinTorqueConfigAnalisis();
break;
}
//..
}
}

最佳答案

However, when I abort that thread from the main thread

那是你的问题。您不应该使用 Thread.Abort。查看 this article 中的“非恶意取消”为了更好的方法。从那里...

The approach I always recommend is dead simple. Have a volatile bool field that is visible both to your worker thread and your UI thread. If the user clicks cancel, set this flag. Meanwhile, on your worker thread, test the flag from time to time. If you see it get set, stop what you're doing.

此外,在 SO thread 中对此进行了很好的讨论.

每条评论:

你拥有这个话题......

Thread AnalisisThread{get{return this.analisisThread;}}

...它执行一个指向...的委托(delegate)

private void MakeAnalisisInOtherThread(object o)

...您也拥有该方法。如果 C++ 接口(interface)没有合理的 .StopAnalysis 方法(或类似的方法),您必须等到分析完成,然后按照文章中的讨论轮询主线程。炸毁线程以停止分析不是正确的做法。

关于c# - 我需要一些在 C# 中使用线程的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1081193/

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