我的目標是創建一個產生初始任務數量(完全相同)的系統。這些任務將抓取並執行一些後臺操作(從數據庫),然後返回,此時應該生成一個新任務並執行相同的操作。異步任務按順序執行?
我已經寫了下面的代碼作爲概念證明,但它似乎像我所有的任務正在執行1乘1,而不是並行。
代碼:
public Form1()
{
InitializeComponent();
}
CancellationTokenSource cts;
private async void button1_Click(object sender, EventArgs e)
{
cts = new CancellationTokenSource();
int reqNumberOfThreads = int.Parse(textBox1.Text);
try
{
await startSlaves(cts.Token, reqNumberOfThreads);
}
catch (OperationCanceledException)
{
MessageBox.Show("Canceled Starting Threads");
}
cts = null;
}
async Task startSlaves(CancellationToken ct, int threadNum)
{
List<Task<int>> allTasks = new List<Task<int>>();// ***Add a loop to process the tasks one at a time until none remain.
for (int x = 0; x < threadNum; x++)
{
allTasks.Add(beginSlaveOperation(ct, x));
}
// ***Add a loop to process the tasks one at a time until none remain.
while (allTasks.Count <= threadNum)
{
// Identify the first task that completes.
Task<int> output = await Task.WhenAny(allTasks);
allTasks.Remove(output);
allTasks.Add(beginSlaveOperation(ct, output.Result));
}
}
public void performExampleImportOperationThread(int inputVal, int whoAmI)
{
System.Threading.Thread.Sleep(inputVal*10);
System.Console.Write("Thread number" + whoAmI.ToString() + "has finished after "+inputVal.ToString()+" secs \n");
}
async Task<int> beginSlaveOperation(CancellationToken ct, int whoAmI)
{
Random random = new Random();
int randomNumber = random.Next(0, 100);//Get command from microSched and remove it from sched
performExampleImportOperationThread(randomNumber, whoAmI);//perform operation
return whoAmI;
}
private void button2_Click(object sender, EventArgs e)
{
if (cts != null)
{
cts.Cancel();
}
}
輸出:
Thread number0has finished after 29 secs Thread number1has finished after 45 secs Thread number2has finished after 59 secs Thread number0has finished after 39 secs Thread number1has finished after 13 secs Thread number2has finished after 44 secs Thread number0has finished after 21 secs Thread number1has finished after 62 secs Thread number2has finished after 62 secs Thread number0has finished after 25 secs Thread number1has finished after 86 secs Thread number2has finished after 10 secs Thread number0has finished after 4 secs Thread number1has finished after 24 secs Thread number2has finished after 84 secs Thread number0has finished after 73 secs Thread number1has finished after 19 secs Thread number2has finished after 72 secs Thread number0has finished after 82 secs
爲什麼downvotes? – paqogomez