回答編集履歴
1
指摘していただいたデッドロックを回避する例を追記
test
CHANGED
@@ -65,3 +65,103 @@
|
|
65
65
|
}
|
66
66
|
|
67
67
|
```
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
ご指摘いただいた通りデッドロックしたため、Windowsフォーム版の例を追記しておきます。
|
72
|
+
|
73
|
+
```C#
|
74
|
+
|
75
|
+
using System;
|
76
|
+
|
77
|
+
using System.Collections.Generic;
|
78
|
+
|
79
|
+
using System.ComponentModel;
|
80
|
+
|
81
|
+
using System.Data;
|
82
|
+
|
83
|
+
using System.Drawing;
|
84
|
+
|
85
|
+
using System.Linq;
|
86
|
+
|
87
|
+
using System.Text;
|
88
|
+
|
89
|
+
using System.Threading;
|
90
|
+
|
91
|
+
using System.Threading.Tasks;
|
92
|
+
|
93
|
+
using System.Windows.Forms;
|
94
|
+
|
95
|
+
|
96
|
+
|
97
|
+
namespace MultiTaskIncrement {
|
98
|
+
|
99
|
+
public partial class Form1 : Form {
|
100
|
+
|
101
|
+
public Form1() {
|
102
|
+
|
103
|
+
InitializeComponent();
|
104
|
+
|
105
|
+
}
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
int num = 0;
|
110
|
+
|
111
|
+
int max = 0;
|
112
|
+
|
113
|
+
public async Task<int> ConvertFile(string in_path, string out_path) {
|
114
|
+
|
115
|
+
return await Task.Run(() => {
|
116
|
+
|
117
|
+
var r = new Random();
|
118
|
+
|
119
|
+
var t = r.Next(500, 1000);
|
120
|
+
|
121
|
+
System.Threading.Thread.Sleep(t);
|
122
|
+
|
123
|
+
this.Invoke((MethodInvoker)delegate() {
|
124
|
+
|
125
|
+
listBox1.Items.Add("[" + (Interlocked.Increment(ref num)) + "/" + max + "] " + in_path + " " + out_path + " " + t);
|
126
|
+
|
127
|
+
});
|
128
|
+
|
129
|
+
return 1;
|
130
|
+
|
131
|
+
});
|
132
|
+
|
133
|
+
}
|
134
|
+
|
135
|
+
|
136
|
+
|
137
|
+
private async void button1_Click(object sender, EventArgs e) {
|
138
|
+
|
139
|
+
num = 0;
|
140
|
+
|
141
|
+
max = 300;
|
142
|
+
|
143
|
+
List<Task<int>> tasklist = new List<Task<int>>();
|
144
|
+
|
145
|
+
for (int i = 0; i < max; i++) {
|
146
|
+
|
147
|
+
tasklist.Add(ConvertFile("aaa" + i, "bbb"));
|
148
|
+
|
149
|
+
}
|
150
|
+
|
151
|
+
await Task.Run(() => {
|
152
|
+
|
153
|
+
Task.WaitAll(tasklist.ToArray());
|
154
|
+
|
155
|
+
});
|
156
|
+
|
157
|
+
MessageBox.Show("owari");
|
158
|
+
|
159
|
+
}
|
160
|
+
|
161
|
+
}
|
162
|
+
|
163
|
+
}
|
164
|
+
|
165
|
+
|
166
|
+
|
167
|
+
```
|