【发布时间】:2015-09-12 07:04:36
【问题描述】:
首先,我必须澄清一下,我是使用线程的新手。现在,我有一个执行多个线程但在不同时间执行的应用程序。我的意思是,我有对象,每个对象在特定时刻执行一个线程。
我会更具体。我有一个任务列表,每个任务都与一个特定的对象相关联。当我单击一个按钮(适用于该对象)时,相关的任务开始运行。在某个时刻,我可以拥有多个线程。这工作正常。问题是当我完成其中一个。我完成了一个线程,其余的也都停止了。
当然,我的实现有问题。我不明白为什么所有线程都停止了。
这是我的实现(我在 Windows 应用程序窗体上的 MVC 中工作):
在我的主要形式中
//This method starts when I press a button from a specific object
private void StartTask( int idtask )
{
int counter = this.Controller.GetTasksSize(); //This is a List<ObjectTask>, this method returns the count
for (int i = 0; i < counter; i++)
{
//GetTasks() returns the List<ObjectTask>
if (this.Controller.GetTasks()[i].idtask == idtask)
{
ThreadStart tsTask = new ThreadStart(() => TaskLoop(this.Controller.GetTasks()[i].idtask,
this.Controller.GetTasks()[i].time,
this.Controller.GetTasks()[i].Mode));
Thread task = new Thread(tsTask);
this.Controller.GetTasks()[i].task = task;
this.Controller.GetTasks()[i].task.Start();
task = null;
break;
}
}
}
private void StopTask(int idtask)
{
int counter = this.Controller.GetTasksSize();
for (int i = 0; i < counter; i++)
{
if (this.Controller.GetTasks()[i].idtask == idtask)
{
try
{
if (this.Controller.GetTasks()[i].task != null && this.Controller.GetTasks()[i].task.IsAlive)
this.Controller.GetTasks()[i].task.Abort();
}
catch (ThreadAbortException e)
{
}
break;
}
}
}
我的 ObjectTask 列表是
public class ObjectTask
{
private int idtask;
public int idtask
{
get { return idtask; }
set { idtask = value; }
}
private int time;
public int time
{
get { return time; }
set { time = value; }
}
private bool Mode;
public bool Mode
{
get { return Mode; }
set { Mode = value; }
}
private Thread task;
public Thread task
{
get { return task; }
set { task = value; }
}
}
同时,当我停止一个线程时,我可以在控制台看到如下信息:
线程 '' (0x1764) 以代码 0 (0x0) 退出。 mscorlib.dll 中出现了“System.Threading.ThreadAbortException”类型的第一次机会异常
我一直在搜索,也看到了这些问题
- A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
- System.Threading.ThreadAbortException occurred in mscorlib.dll occuring persitently
- Stopping only one thread
- Multi Threading C# Windows Forms
但没有人帮助我。
如果需要更多信息,请告诉我。
【问题讨论】:
-
无论何时在线程中运行任何代码,都必须为该方法处理 ThreadExeption 以便它正常退出
-
抱歉,问题名称已更改。我把 C# Windows Form App.我会尝试编辑它
标签: c# .net multithreading winforms