后端开发

网络新概念,云计算、大数据、O2O、电商。。。。

https://www.bytehide.com/blog/task-run-csharp

// This example represent multiple asynchronous tasks
List<Task> tasks = new List<Task>();
for (int i = 0; i < 5; i++)
{    
    int taskNum = i;  // To avoid the closure variable trap
    tasks.Add(Task.Run(async () =>
    {        
        // Simulate a long-running task
        await Task.Delay(1000);
        Console.WriteLine($"Task {taskNum} completed!");
    }));
};
Console.WriteLine("Waiting for all tasks to complete...");
await Task.WhenAll(tasks);
Console.WriteLine("All tasks completed!");


异步实践例子,while循环查询数据然后进行http请求,每次100个线程同时请求,直到数据查询完毕


int intResult = 100;
while (intResult == 100)
    intResult = await listData();

private async Task<int> listData()
        {
            DataSet ds = GetData();//Search From DataBase

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count >= 1)
            {
                List<Task> tasks = new List<Task>();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    taskNum = taskNum + 1;
                    tasks.Add(Task.Run(async () =>
                    {
                        string msg = await RunPost(row);//post data
                        Debug.WriteLine($"Task {row["id"]} completed!" + msg);
                    }));
                }

                Debug.WriteLine("000Waiting for all tasks to complete...");
                await Task.WhenAll(tasks);
                Debug.WriteLine("All tasks completed!");
                if (tasks.Count == 100)
                    return 100;//having more 
                else
                    return 0;
            }
            return 0;
        }


TAG: 多线程