【发布时间】:2010-08-14 23:19:43
【问题描述】:
我是 c# 中的多线程新手,对所有线程的东西感到困惑。 这是我想要的:
public class TheClass
{
Thread _thread;
bool _isQuitting;
bool _isFinished;
object jobData;
public void Start()
{
jobData = new object();
_thread = new Thread(new ThreadStart(Run));
_thread.Start();
}
private void Run()
{
while (!_isQuitting)
{
lock (jobData) // or should i use mutex or monitor?
{
DoStuff();
}
// sleep till get triggered
}
DoCleanupStuff();
_isFinished = true;
}
public void AddJob(object param)
{
jobData = param;
//wake up the thread
}
public void Stop()
{
_isQuitting = true;
//wake up & kill the thread
//wait until _isFinished is true
//dispose the _thread object
}
}
在这个类中,实现注释掉的短语和整体性能的最有效方法是什么?
【问题讨论】:
-
只是几个cmets: ①你的
jobData对象最初是空的,所以如果用户在调用AddJob之前调用Run,它就会崩溃。要解决此问题,您可以将object jobdata;更改为object jobdata = new object();。 ②Run方法好像根本没有用到它的参数,所以你可以直接去掉它,用ThreadStart代替ParameterizedThreadStart。
标签: c# multithreading events triggers