str*_*rxz 2 c# multithreading process
我在C#中开发一个软件,它通过Wrapper使用C++ .dll文件中的静态函数.
问题是这些函数中的一些是缓慢且不稳定的,所以为了解决这个问题,我创建了一个执行它们的Thread.但是,当我从主线程中止该线程时,程序不允许我再次使用这些函数,即使我每次调用函数时都定义了一个新的线程实例.
有什么办法可以解决这个问题吗?
提前致谢.
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;
}
//..
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我从主线程中止该线程时
那是你的问题.你不应该使用Thread.Abort.退房"为非作恶取消" 这篇文章的一个更好的办法.从那里 ...
我总是推荐的方法很简单.拥有一个对工作线程和UI线程都可见的volatile bool字段.如果用户单击"取消",请设置此标志.同时,在您的工作线程上,不时测试该标志.如果你看到它被设置,停止你正在做的事情.
另外,在这个SO线程中对此进行了非常好的讨论.
每条评论:
你拥有这个线程......
Thread AnalisisThread{get{return this.analisisThread;}}
Run Code Online (Sandbox Code Playgroud)
...它执行指向...的委托
private void MakeAnalisisInOtherThread(object o)
Run Code Online (Sandbox Code Playgroud)
...你也拥有那种方法.如果C++接口没有合理的.StopAnalysis方法(或类似的东西),则必须等到分析完成后再按照文章中的讨论轮询主线程.炸毁你的线程以停止分析是不对的.