C#并行计算Task使用

csharp

浏览数:1,018

2019-1-8


C#并行计算Task使用

/// <summary>
/// 在Framework 4.0中使用
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
    StringBuilder builder = new StringBuilder();
    builder.Append("******开始处理" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "\r\n");
    List<Task<string>> list = new List<Task<string>>();
    for (int i = 0; i < 10; i++)
    {
        int val = i;
        Task<string> task = new Task<string>(() =>
        {
            Thread.Sleep(5 * 1000);

            return val + "-Done-" + Thread.CurrentThread.ManagedThreadId;
        });
        task.Start();

        list.Add(task);
    }
    
    Task.WaitAll(list.ToArray());
    foreach (var task in list)
    {
        string val = task.Result;
        builder.Append(val + "\t" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "\r\n");
    }

    builder.Append("******结束处理" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "\r\n");
    System.IO.File.WriteAllText("d:/123.log", builder.ToString(), System.Text.Encoding.UTF8);
}//********************需要返回值**************************//
//入口事件方法
private void button2_Click(object sender, EventArgs e)
{
    Invoke();
}

private async void Invoke()
{
    List<Task<string>> list = new List<Task<string>>();
    StringBuilder builder = new StringBuilder();
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    builder.Append("******开始处理" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "\r\n");
    //先提交任务
    for (int i = 0; i < 10; i++)
    {
        Task<string> task = Test(i);
        list.Add(task);
    }
    //取得返回值
    foreach (var task in list)
    {
        string result = await task;
        builder.Append(result + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "\r\n");
    }
    stopwatch.Stop();
    builder.Append("******结束处理" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "\r\n");
    builder.Append("******总共耗时(毫秒):" + stopwatch.ElapsedMilliseconds + "\r\n");

    System.IO.File.WriteAllText("d:/123.log", builder.ToString(), System.Text.Encoding.UTF8);

}

private async Task<string> Test(int i)
{
    return await Task.Run<string>(() =>
    {
        //模拟耗时操作
        Thread.Sleep(20 * 1000);
        return i + "-Done-" + Thread.CurrentThread.ManagedThreadId + "\t";
    });
}

//******************不需要返回值*****************************//
private void button2_Click(object sender, EventArgs e)
{
    Invoke();
}

private void Invoke()
{
    List<Task> list = new List<Task>();
    StringBuilder builder = new StringBuilder();
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    builder.Append("******开始处理" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "\r\n");
    for (int i = 0; i < 10; i++)
    {
        Task task = Test(i);
        task.Start();
        list.Add(task);
    }

    Task.WaitAll(list.ToArray());
    stopwatch.Stop();
    builder.Append("******结束处理" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "\r\n");
    builder.Append("******总共耗时(毫秒):" + stopwatch.ElapsedMilliseconds + "\r\n");

    System.IO.File.WriteAllText("d:/123.log", builder.ToString(), System.Text.Encoding.UTF8);
}

private Task Test(int i)
{
    return new Task(() =>
        {
            //模拟耗时操作
            Thread.Sleep(20 * 1000);
        });
}

-------------
Task.Factory.StartNew();