C#多线程

      C#里面创建多线程,使用“Thread”类。假设Do方法有一个string参数,那么就要使用“ParameterizedThreadStart”进行实例化,详细如下。
Thread th = new Thread(new ParameterizedThreadStart(Do)); th.IsBackground=true; th.Start(your value here);
     看这句代码,如果 Do 方法执行完成,该线程就自动销毁了。如果该线程不是后台线程,应用程序域退出时,它也会自动结束。当然,还有其它的方式用意强制结束线程,但是这些方法
都和你的 Do 方法要执行任务相关,有时候会造成你显式的调用了 Abort,但是它仍在运行。通常会在Do方法内把任务分解的足够细,然后通过 ManualResetEvent 来控制线程的退出。
      要在应用程序退出时销毁可以,这要看你是什么应用程序,如果是WinForm,你只要执行下面语句:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
if(this.thread != null)
{
this.thread.Suspend();
this.thread.Abort();
}
}
catch
{
MessageBox.Show("异常终止线程");
}
}
其实,只要线程的宿主进程销毁了,线程就会自动销毁。

可以把多个线程放入一个Dictionary中,Dictionary<string,Thread>,其中string为“标识”(可以通过Name获取)。

可以通过Start,Suspend或者Reset方法控制启停(注意,这些方法对于同步而言是过时的,但单纯对于控制线程”停止“和”启动“是可以的)。


namespace Processing
{
public class ETLProcess
{
public Dictionary<string,Thread> threadlists;//线程列表
public ETLProcess()
{
threadlists = new Dictionary<string, Thread>();
}

public bool CreateThead(string ETLTableName)
{
bool flag=false;
//TableName = ETLTableName;
try
{
Thread th = new Thread(new ParameterizedThreadStart(Do));
th.IsBackground = true;
th.Name = ETLTableName;
th.Start(ETLTableName);

threadlists.Add(ETLTableName, th);


flag = true;
}
catch (Exception ex)
{
flag = false;
}

return flag;
}


public void Do(object TableName)
{
while (true)
{
Processing(TableName.ToString());

//Thread.Sleep(60000);//线程一分钟跑一次

Thread.Sleep(10000);
}


}

public bool SuspendThread(string threadname)
{
bool flag = false;
try
{
threadlists[threadname].Suspend();

flag = true;
}
catch (Exception ex)
{
flag = false;
}

return flag;
}


public bool SuspendAbort(string threadname)
{
bool flag = false;
try
{
threadlists[threadname].Abort();
flag = true;
}
catch (Exception ex)
{
flag = false;
}

return flag;
}
}
}

最后,要注意线程最外围要用“While”保证线程的持续运行。如果是多线程访问数据库,注意线程间“数据库连接资源Conn”对象的竞争。

原文地址:https://www.cnblogs.com/ssol/p/2851508.html