資源簡(jiǎn)介
多線程有很好的并發(fā)性即無序性,在某些特殊情況下需要用到多線程然而又要使其具備順序性,這種時(shí)候就有了一個(gè)特殊的場(chǎng)景那就是多線程順序執(zhí)行,在現(xiàn)在VS2015中Task自帶了順序執(zhí)行的方法,但在此之前的舊項(xiàng)目中如果需要使用多線程順序執(zhí)行該怎么辦呢?Task又是怎么實(shí)現(xiàn)的呢?這里提供了一種類似Task順序執(zhí)行多線程的實(shí)現(xiàn)(可能跟Task的原理有很大區(qū)別),希望對(duì)大家能有幫助,對(duì)此類問題的實(shí)現(xiàn)有更好的思路和技巧的同學(xué)歡迎留言,大家一起探討。
代碼片段和文件信息
using?System;
using?System.Collections.Generic;
using?System.Threading;
namespace?_3vjDemos
{
????[Serializable]
????public?class?OrderedExecuteThread
????{
????????public?OrderedExecuteThread?ThreadFront?{?get;?set;?}
????????[System.xml.Serialization.xmlIgnore]
????????public?Actionject>?ActionDoing?{?get;?set;?}????????
????????[System.xml.Serialization.xmlIgnore]
????????public?Thread?Thread?{?get;?set;?}????????
????????public?bool?IsCurrentExcuted?{?get;?set;?}
????????public?bool?IsCurrentStarted?{?get;?set;?}
????????public?bool?IsCurrentDealt?{?get;?set;?}
????????public?int?OrderedIndex?{?get;?set;?}??????
????????public?void?ExecuteThread(object?obj)
????????{
????????????try
????????????{
????????????????IsCurrentDealt?=?true;
????????????????if?(ActionDoing?!=?null)
????????????????{
????????????????????ActionDoing.Invoke(obj);//DoSomeThing
????????????????}
????????????????Thread.Sleep(new?Random().Next(0?200)?*?100);
????????????????while?(true)
????????????????{
????????????????????if?((ThreadFront?==?null?||?ThreadFront.Thread?==?null?||?ThreadFront.IsCurrentExcuted)?&&?!this.IsCurrentExcuted&&!IsCurrentStarted)
????????????????????{
????????????????????????Thread.Start(this.OrderedIndex);
????????????????????????this.IsCurrentStarted?=?true;
????????????????????}
????????????????????Thread.Sleep(50);
????????????????????if?(!Thread.IsAlive?&&?IsCurrentStarted)
????????????????????{
????????????????????????this.IsCurrentExcuted?=?true;
????????????????????????break;
????????????????????}
????????????????}
????????????}
????????????catch?(Exception?ex)
????????????{
????????????????Console.WriteLine(“Thread?“?+?this.OrderedIndex.ToString()?+?“?exit?by?“?+?ex.Message);
????????????}
????????}
????}
????public?class?OrderedExecuteThreads
????{
????????public?List
評(píng)論
共有 條評(píng)論