参考:https://www.jb51.net/article/237222.htm
//不卡主线程,获取返回值。
List<Task<int>> tasks = new List<Task<int>>();
tasks.Add(Task.Run(()=>{return 1;}));
//返回的是一个int类型的集合
var results = await Task.WhenAll(tasks);
//单个Task返回
var res = await Task.Run(()=>{return 1;});

.net设置超时时间,取消线程,接收返回数据。
/// <summary>
/// Task超时则取消Task
/// </summary>
/// <returns></returns>
/// <exception cref="TimeoutException"></exception>
public async Task TaskTimeOut()
{
    List<Task<TaskResult>> tasks = new List<Task<TaskResult>>();
    for (int i = 0; i < 5; i++)
    {
        int k = i;
        tasks.Add(Task.Run(async () =>
        {
            try
            {
                var cancellationTokenSource = new CancellationTokenSource();
                var cancellationToken = cancellationTokenSource.Token;
                // 设置超时时间为2秒
                var timeoutTask = Task.Delay(2000, cancellationToken);

                var task = Task.Run(() =>
                {
                    // 这里放置你的长时间运行的任务代码
                    // 例如:
                    Thread.Sleep(k * 1000); // 模拟长时间运行的操作
                    return "任务" + k + "完成";
                }, cancellationToken);

                var completedTask = await Task.WhenAny(task, timeoutTask);
                if (completedTask == timeoutTask)
                {
                    // 超时逻辑
                    cancellationTokenSource.Cancel(); // 取消任务
                    throw new TimeoutException("任务" + k + "执行超时。");
                }
                else
                {
                    // 任务正常完成逻辑
                    var result = await task;
                    return new TaskResult() { Message = "任务" + k + "结果:" + result, Status = "0" };
                }
            }
            catch (Exception ex)
            {
                return new TaskResult() { Message = "任务" + k + "异常:" + ex.Message, Status = "-1" };
            }
        }));
    }
    //所有任务跑完
    var taskAfter = await Task.WhenAll(tasks);
    if (taskAfter != null)
    {
        var options = new JsonSerializerOptions
        {
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All)
        };
        foreach (var item in taskAfter)
        {
            UpdateMsg("执行结果:" + JsonSerializer.Serialize(item, options));
        }
    }
}

 啊啊啊啊

 /// <summary>
 /// 更新消息框
 /// </summary>
 /// <param name="msg"></param>
 public void UpdateMsg(string msg)
 {
     if (txtMsg.InvokeRequired)
     {
         Action<string> action = UpdateMsg;
         Invoke(action, msg);
         return;
     }
     txtMsg.AppendText(msg + "\r\n");
     //滚动到底部
     txtMsg.ScrollToCaret();
 }

 

posted on 2024-05-22 15:23  邢帅杰  阅读(121)  评论(0编辑  收藏  举报