动作中的C#异步

Ori*_*ael 4 c# action task

我想编写一个接受几个参数的方法,包括一个动作和一个重试量并调用它。

所以我有这段代码:

public static IEnumerable<Task> RunWithRetries<T>(List<T> source, int threads, Func<T, Task<bool>> action, int retries, string method)
    {
        object lockObj = new object();
        int index = 0;

        return new Action(async () =>
        {
            while (true)
            {
                T item;
                lock (lockObj)
                {
                    if (index < source.Count)
                    {
                        item = source[index];
                        index++;
                    }
                    else
                        break;
                }

                int retry = retries;
                while (retry > 0)
                {
                    try
                    {
                        bool res = await action(item);
                        if (res)
                            retry = -1;
                        else
                            //sleep if not success..
                            Thread.Sleep(200);

                    }
                    catch (Exception e)
                    {
                        LoggerAgent.LogException(e, method);
                    }
                    finally
                    {
                        retry--;
                    }
                }
            }
        }).RunParallel(threads);
    }
Run Code Online (Sandbox Code Playgroud)

RunParallel是Action的扩展方法,其外观如下所示:

public static IEnumerable<Task> RunParallel(this Action action, int amount)
    {
        List<Task> tasks = new List<Task>();
        for (int i = 0; i < amount; i++)
        {
            Task task = Task.Factory.StartNew(action);
            tasks.Add(task);
        }
        return tasks;
    }
Run Code Online (Sandbox Code Playgroud)

现在的问题是:线程只是消失或崩溃而没有等待操作完成。

我编写了以下示例代码:

private static async Task ex()
    {
        List<int> ints = new List<int>();
        for (int i = 0; i < 1000; i++)
        {
            ints.Add(i);
        }

        var tasks = RetryComponent.RunWithRetries(ints, 100, async (num) =>
        {
            try
            {
                List<string> test = await fetchSmthFromDb();
                Console.WriteLine("#" + num + "  " + test[0]);
                return test[0] == "test";
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return false;
            }

        }, 5, "test");

        await Task.WhenAll(tasks);
    }
Run Code Online (Sandbox Code Playgroud)

fetchSmthFromDb是一个简单的Task>,它可以从db中获取某些内容,并且在本示例之外进行调用时也可以正常工作。

每当List<string> test = await fetchSmthFromDb();调用该行时,该线程似乎正在关闭并且Console.WriteLine("#" + num + " " + test[0]);甚至没有被触发,而且在调试断点时也永远不会命中。

最终工作守则

private static async Task DoWithRetries(Func<Task> action, int retryCount, string method)
    {
        while (true)
        {
            try
            {
                await action();
                break;
            }
            catch (Exception e)
            {
                LoggerAgent.LogException(e, method);
            }

            if (retryCount <= 0)
                break;

            retryCount--;
            await Task.Delay(200);
        };
    }

    public static async Task RunWithRetries<T>(List<T> source, int threads, Func<T, Task<bool>> action, int retries, string method)
    {
        Func<T, Task> newAction = async (item) =>
        {
            await DoWithRetries(async ()=>
            {
                await action(item);
            }, retries, method);
        };
        await source.ParallelForEachAsync(newAction, threads);
    }
Run Code Online (Sandbox Code Playgroud)

Ser*_*nov 11

问题在这一行:

return new Action(async () => ...
Run Code Online (Sandbox Code Playgroud)

您可以使用异步lambda启动异步操作,但不要返回要等待的任务。也就是说,它在工作线程上运行,但是您永远都不会知道它何时完成。并且您的程序在异步操作完成之前终止-这就是为什么您看不到任何输出的原因。

它必须是:

return new Func<Task>(async () => ...
Run Code Online (Sandbox Code Playgroud)

更新

首先,您需要分割方法的职责,因此不要将重试策略(不应硬编码为布尔结果的检查)与并行运行的任务混合使用。

然后,如前所述,您将while (true)循环运行100次,而不是并行执行操作。

正如@MachineLearning指出的那样,请使用Task.Delay代替Thread.Sleep

总体而言,您的解决方案如下所示:

using System.Collections.Async;

static async Task DoWithRetries(Func<Task> action, int retryCount, string method)
{
    while (true)
    {
        try
        {
            await action();
            break;
        }
        catch (Exception e)
        {
            LoggerAgent.LogException(e, method);
        }

        if (retryCount <= 0)
            break;

        retryCount--;
        await Task.Delay(millisecondsDelay: 200);
    };
}

static async Task Example()
{
    List<int> ints = new List<int>();
    for (int i = 0; i < 1000; i++)
        ints.Add(i);

    Func<int, Task> actionOnItem =
        async item =>
        {
            await DoWithRetries(async () =>
            {
                List<string> test = await fetchSmthFromDb();
                Console.WriteLine("#" + item + "  " + test[0]);
                if (test[0] != "test")
                    throw new InvalidOperationException("unexpected result"); // will be re-tried
            },
            retryCount: 5,
            method: "test");
        };

    await ints.ParallelForEachAsync(actionOnItem, maxDegreeOfParalellism: 100);
}
Run Code Online (Sandbox Code Playgroud)

您需要使用AsyncEnumerator NuGet包才能使用命名空间中的ParallelForEachAsync扩展方法System.Collections.Async