c# oracle 线程池,C#中控制线程池的执行顺序

在使用线程池时,当用线程池执行多个任务时,由于执行的任务时间过长,会导制两个任务互相执行,如果两个任务具有一定的操作顺序,可能会导制不同的操作结果,这时,就要将线程池按顺序操作。下面先给一段代码,该代码是不按顺序对线程池进行操作的,代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

AutoResetEvent autoEvent = new AutoResetEvent(false);

ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), autoEvent);

ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod), autoEvent);

Console.ReadLine();

}

static void ThreadMethod(object stateInfo)

{

for (int i = 0; i < 100;i++ )

Console.WriteLine("ThreadOne, executing ThreadMethod, " + "is {0}from the thread pool.", Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");

}

static void WorkMethod(object stateInfo)

{

for (int i = 0; i < 100; i++)

Console.WriteLine("ThreadTwo, executing WorkMethod");

}

}

}

运行结果如图1、图2所示。

c5e750aa24566926b41164dbbf90e384.png

图1  运行结果的上半部

35f033dc80453d3cd3b007075cbf1b08.png

图2  运行结果的下半部

从图1、图2可以看出,在使用线程池对线程进行操作时,由于各任务的时间过长,多个任务的线程可能会交互操作,那么,如何才能将线程池按指定的顺序进行操作呢?主要是用AutoResetEvent类来实现的。

可以用AutoResetEvent类的WaitOne方法阻止线程,然后只执行当前操作的线程池,当遇到AutoResetEvent类的Set方法后,将当前线程设置为终止状态,执行其他等待的线程。修改后的代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

AutoResetEvent autoEvent = new AutoResetEvent(false);

ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), autoEvent);

autoEvent.WaitOne();

ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod), autoEvent);

autoEvent.WaitOne();

Console.ReadLine();

}

static void ThreadMethod(object stateInfo)

{

for (int i = 0; i < 100;i++ )

Console.WriteLine("ThreadOne, executing ThreadMethod, " + "is {0}from the thread pool.", Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");

((AutoResetEvent)stateInfo).Set();

}

static void WorkMethod(object stateInfo)

{

for (int i = 0; i < 100; i++)

Console.WriteLine("ThreadTwo, executing WorkMethod");

((AutoResetEvent)stateInfo).Set();

}

}

}

运行结果如下:

639d6a5c8afab37a60d3f7318c1ec139.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值