先把测试代码记录一下
int c = 0; for (int i = 0 ; i < 100 ; i++) { int j = i; Task.Run(() => { Console.WriteLine($"乱序{j}"); return j; }).ContinueWith(tt => { while (true) { if (j == c) { Console.WriteLine($"c{c}乱序{tt.Result}顺序{j}"); Interlocked.Increment(ref c); break; } } });
输出:
乱序0
乱序1
乱序2
乱序3
c0乱序0顺序0
c1乱序1顺序1
c2乱序2顺序2
c3乱序3顺序3
乱序7
乱序6
乱序4
c4乱序4顺序4
乱序8
乱序9
乱序5
c5乱序5顺序5
乱序12
乱序13
乱序10
乱序11
c6乱序6顺序6
c7乱序7顺序7
c8乱序8顺序8
c9乱序9顺序9
c10乱序10顺序10
乱序18
乱序15
乱序14
乱序16
乱序17
c11乱序11顺序11
c12乱序12顺序12
c13乱序13顺序13
c14乱序14顺序14
c15乱序15顺序15
c16乱序16顺序16
c17乱序17顺序17
c18乱序18顺序18
乱序26
乱序25
乱序23
乱序19
c19乱序19顺序19
乱序27
乱序20
c20乱序20顺序20
乱序28
乱序22
乱序21
c21乱序21顺序21
c22乱序22顺序22
c23乱序23顺序23
乱序29
乱序31
乱序30
乱序24
c24乱序24顺序24
c25乱序25顺序25
c26乱序26顺序26
c27乱序27顺序27
乱序35
乱序33
乱序32
乱序34
c28乱序28顺序28
c29乱序29顺序29
c30乱序30顺序30
c31乱序31顺序31
乱序40
乱序38
c32乱序32顺序32
c33乱序33顺序33
c34乱序34顺序34
c35乱序35顺序35
乱序44
乱序42
乱序43
乱序41
乱序39
乱序37
乱序36
c36乱序36顺序36
乱序45
c37乱序37顺序37
c38乱序38顺序38
c39乱序39顺序39
c40乱序40顺序40
乱序49
乱序46
c41乱序41顺序41
乱序50
c42乱序42顺序42
c43乱序43顺序43
乱序52
乱序51
c44乱序44顺序44
c45乱序45顺序45
c46乱序46顺序46
乱序55
乱序54
乱序53
乱序48
乱序47
c47乱序47顺序47
乱序56
c48乱序48顺序48
乱序57
c49乱序49顺序49
c50乱序50顺序50
c51乱序51顺序51
c52乱序52顺序52
c53乱序53顺序53
c54乱序54顺序54
c55乱序55顺序55
c56乱序56顺序56
c57乱序57顺序57
乱序60
乱序59
乱序65
乱序61
乱序64
乱序66
乱序63
乱序58
c58乱序58顺序58
乱序67
c59乱序59顺序59
c60乱序60顺序60
c61乱序61顺序61
乱序70
乱序68
乱序62
c62乱序62顺序62
乱序71
c63乱序63顺序63
c64乱序64顺序64
乱序73
乱序72
乱序69
c65乱序65顺序65
乱序74
c66乱序66顺序66
c67乱序67顺序67
乱序76
c68乱序68顺序68
c69乱序69顺序69
c70乱序70顺序70
c71乱序71顺序71
c72乱序72顺序72
c73乱序73顺序73
c74乱序74顺序74
乱序83
乱序79
乱序77
乱序75
c75乱序75顺序75
c76乱序76顺序76
c77乱序77顺序77
乱序86
乱序82
乱序78
乱序80
乱序84
乱序81
乱序85
c78乱序78顺序78
乱序87
c79乱序79顺序79
c80乱序80顺序80
c81乱序81顺序81
c82乱序82顺序82
c83乱序83顺序83
c84乱序84顺序84
c85乱序85顺序85
c86乱序86顺序86
c87乱序87顺序87
乱序96
乱序88
c88乱序88顺序88
乱序89
c89乱序89顺序89
乱序98
乱序93
乱序91
乱序97
乱序90
c90乱序90顺序90
乱序99
乱序95
乱序92
c91乱序91顺序91
c92乱序92顺序92
乱序94
c93乱序93顺序93
c94乱序94顺序94
c95乱序95顺序95
c96乱序96顺序96
c97乱序97顺序97
c98乱序98顺序98
c99乱序99顺序99