簡體   English   中英

帶有await的ThreadAbortException

[英]ThreadAbortException with await

我正面臨着一個奇怪的錯誤。 我有100個長時間運行的任務,我想在同一時間運行其中的10個。

我發現了一些非常類似於我需要的東西:限制部分中的http://msdn.microsoft.com/en-us/library/hh873173%28v=vs.110%29.aspx

這里是簡化后的C#代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main(string[] args)
        {
            Test();
        }

        public static async void Test()
        {
            var range = Enumerable.Range(1, 100).ToList();

            const int CONCURRENCY_LEVEL = 10;
            int nextIndex = 0;
            var matrixTasks = new List<Task>();

            while (nextIndex < CONCURRENCY_LEVEL && nextIndex < range.Count())
            {
                int index = nextIndex;
                matrixTasks.Add(Task.Factory.StartNew(() => ComputePieceOfMatrix()));
                nextIndex++;
            }

            while (matrixTasks.Count > 0)
            {
                try
                {
                    var imageTask = await Task.WhenAny(matrixTasks);
                    matrixTasks.Remove(imageTask);
                }
                catch (Exception e)
                {
                    Console.Write(1);
                    throw;
                }

                if (nextIndex < range.Count())
                {
                    int index = nextIndex;
                    matrixTasks.Add(Task.Factory.StartNew(() => ComputePieceOfMatrix()));
                    nextIndex++;
                }
            }

            await Task.WhenAll(matrixTasks); 
        }

        private static void ComputePieceOfMatrix()
        {
            try
            {
                for (int j = 0; j < 10000000000; j++) ;
            }
            catch (Exception e)
            {
                Console.Write(2);
                throw;
            }
        }
    }
}

從單元測試運行時,在ComputePieceOfMatrix中有一個ThreadAbortException。

你有什么主意嗎 ?

編輯:

根據評論,我試過這個:

static void Main(string[] args)
{
    Run();
}

private static async void Run()
{
    await Test();
}

public static async Task Test()
{
    var range = Enumerable.Range(1, 100).ToList();

但它完全一樣。

1.您的代碼會導致異常

try
{
    for (int j = 0; j < 10000000000; j++) ;
}
catch (Exception e)
{
    Console.Write(2);
    throw;
}

只是一個簡單的溢出異常因為10000000000 - 是長和j計數器int。

2.在子線程完成之前,您的主踏板正在退出。 很可能你得到了ThreadAbortException,因為Threads被運行時關閉了

3.await Test() - 正確地調用Test(),並等待Task.WhenAny也沒有等待

Test()的返回類型更改為Task ,然后等待該Task完成,直到程序結束。

static void Main(string[] args)
{
    Test().Wait();
}

public static async Task Test()
{
    // ...
}

我會將你的測試從void更改為Task返回類型,並在main方法中代替Test();

Task t = Test();
t.Wait();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM