List<Thread> threadList = new List<Thread>(); for (int i = 0; i < list.Count; i++)
{
Thread thread = new Thread(new ParameterizedThreadStart(Action));
thread.SetApartmentState(ApartmentState.STA);
threadList.Add(thread);
} for (int j = 0; j < list.Count; j++)
{
threadList[j].Start(list[j]);//我想释放该线程的资源
} System.Threading.Thread.Sleep(10000); 注:该函数我每隔10s调用一次的 threadList中的线程是同步执行的!
所以我希望的是 在第二个for 循环之后 把 threadlist中的线程资源都释放光!
当然,其他方法也行,只要能释放资源就好
{
Thread thread = new Thread(new ParameterizedThreadStart(Action));
thread.SetApartmentState(ApartmentState.STA);
threadList.Add(thread);
} for (int j = 0; j < list.Count; j++)
{
threadList[j].Start(list[j]);//我想释放该线程的资源
} System.Threading.Thread.Sleep(10000); 注:该函数我每隔10s调用一次的 threadList中的线程是同步执行的!
所以我希望的是 在第二个for 循环之后 把 threadlist中的线程资源都释放光!
当然,其他方法也行,只要能释放资源就好
主线程会释放资源的 ,但是不知道 函数中的这些 ThreadList中的线程会不会跟着释放
在整个程序退出时,线程将自动消毁,可在ACTION中设置一个标记令执行其的线程暂停,如
while(true)
{
if( !isStop )
{
执行
}
Thread.Sleep(1);//调用线程暂停,避免CPU占用率100%
}
{
try
{
Log.LogEvent(this.ThreadName + " start!");
}
catch (Exception exp)
{
try
{
Log.LogEvent("Error Message:" + exp.Message + "\n Error StackTrace:" + exp.StackTrace, EventLogEntryType.Error);
}
finally { }
} while (!this.StopFlag)
{
try
{
IList<Student> list = StudentDao.GetStudents(); List<Thread> threadList = new List<Thread>(); for (int i = 0; i < list.Count; i++)
{
Thread thread = new Thread(new ParameterizedThreadStart(Action));
thread.SetApartmentState(ApartmentState.STA);
threadList.Add(thread);
} for (int j = 0; j < list.Count; j++)
{
threadList[j].Start(list[j]);
} System.Threading.Thread.Sleep(10000); }
catch (Exception exp)
{
}
} try
{
Log.LogEvent(this.ThreadName + " is stopped!");
}
finally { }
}我的函数整体就是这样的,我做的是一个Service的!不知道它会不会自动释放资源的
线程运行时, CLR 内部会对线程有个引用, 结束时, 该引用至空, 所以一般来说, 线程运行完会自动释放
但这里有个前提, 即程序中其他地方没有保留对该线程的引用楼主的程序中有个 List 保存了所有的 Thread 引用, 当线程运行完毕, 则需要同时至空 List