C# .Net - 如何让应用程序等到库中创建的所有线程都完成

C# .Net - How to make application wait until all threads created in Library are finished

我正在尝试创建一个日志记录库,在调用应用程序关闭之前一切正常。当调用应用程序关闭时,任何未完成的线程都会被杀死,特定的日志也会丢失。

到目前为止,应用程序甚至在前 10 个线程完成之前就退出了。我需要有关如何使应用程序等待直到库创建的所有线程都完成的帮助。

注意: 我得到的要求是这样的。修改应该只在 class 'Logging' 中,因为这将是一个库并将提供给最终用户。必须在其中处理应用程序关闭期间的日志记录问题。这是我现在遇到的麻烦。

或者,一种解决方案,例如在日志记录 class 中创建事件以触发所有日志记录完成,并要求用户在该事件上调用应用程序退出是可能的,但我试图避免这样做,因为它增加了负担最终用户并增加了实施的复杂性。他们有可能跳过它,这是我不希望的。我正在寻找用户应该做的解决方案 'Logging.AddException(....)' 然后忘记它。

请帮忙。如果您对这个想法不清楚,请提出意见。

这是完整的代码摘要,您可以将其放入控制台应用程序中。 注意:在案例 1 和案例 2 中查找评论。

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

namespace MultithreadKeepAlive
{
class Program
{
    static void Main(string[] args)
    {
        LogLoadTest();
        Logging.AddExceptionEntryAsync(new Exception("Last Exception"));

        /*
         * USE CASE 1: Enable the below lines and you will see how long it is supposed to take.
         * Notice that currentDomain_ProcessExit will not trigger if below gets uncommented
         */
        //Console.WriteLine("Main thread wait override");
        //Console.ReadLine();
    }

    static void LogLoadTest()
    {
        //In real world this will be called from any place of application like startup or just after application shutdown is initiated.
        //: NOTICE: Unlike the sample here, this will never be on loop and I am not looking for handling multithreads in this class.
        //      That responsibility I am planning to assign to Logging class.
        // AND ALSO the class Logging is going to be in a seperate signed assembly where user of this class ('Program') should not worry about multithreads.
        Task t;
        for (int i = 0; i < 40; i++)
        {
           t =  Logging.AddExceptionEntryAsync(new Exception("Hello Exception " + i), "Header info" + i);
        }
    }
}

public class Logging
{
    static List<Task> tasks = new List<Task>();

    static AppDomain currentDomain;
    static Logging()
    {
        currentDomain = AppDomain.CurrentDomain;
        currentDomain.ProcessExit += currentDomain_ProcessExit;
    }

    public static async Task AddExceptionEntryAsync(Exception ex, string header = "")
    {
        Task t = Task.Factory.StartNew(() => AddExceptionEntry(ex, header));
        tasks.Add(t);
        await t;
    }

    public static void AddExceptionEntry(Exception ex, string header)
    {
        /* Exception processing and write to file or DB. This might endup in file locks or 
         * network or any other cases where it will take delays from 1 sec to 5 minutes. */
        Thread.Sleep(new Random().Next(1, 1000));
        Console.WriteLine(ex.Message);
    }

    static void currentDomain_ProcessExit(object sender, EventArgs e)
    {
            Console.WriteLine("Application shutdown triggerd just now.");
            Process.GetCurrentProcess().WaitForExit();    //1st attempt.
            //Task.WaitAll(tasks.ToArray()); //2nd attempt
            while (tasks.Any(t => !t.IsCompleted)) //3rd attempt.
            {
            }
            /* USE CASE 2: IF WORKING GOOD, THIS WILL BE DISPLAYED IN CONSOLE AS LAST 
             * MESSAGE OF APPLICATION AND WILL WAIT FOR USER. THIS IS NOT WORKING NOW.*/
            Console.WriteLine("All complete"); //this message should show up if this work properly
            Console.ReadLine(); //for testing purpose wait for input from user after every thread is complete. Check all 40 threads are in console.
    }
}

}

你可以试试

Task.WaitAll(tasks);

这会等待所有提供的任务对象完成执行。

更新:使用async/await

通过 async 和 await,我们规范并阐明了异步、非阻塞方法的开始和结束方式。异步方法可以 return 只能无效或任务。

static void Main()
{
// Create task and start it.
// ... Wait for it to complete.
Task task = new Task(AsyncMethod);
task.Start();
task.Wait();
}

public static async void AsyncMethod(){
await AnotherMehod();}

static async Task AnotherMehod() { //TODO}

第 1 步:如果您不希望调度程序参与,请考虑更改为 Task.Run()。我还假设您想等到所有异步任务完成。

public static AddExceptionEntry(Exception ex, string header = "")
{
    Task t = Task.Factory.StartNew(() => AddExceptionEntry(ex, header));
    tasks.Add(t);

    WaitForExecutionAsync().ConfigureAwait(true);
}

public static async Task WaitForExecutionAsync()
{
    if(tasks.Count >0) 
        await Task.WhenAll(tasks.ToArray());
    // Raise Event.
}

要阻止,只需将此调用为 运行 同步与异步:

WaitForExecution().GetAwaiter().GetResult();

到目前为止,我自己找到了解决方法。

    /// <summary>
    /// Makes the current thread Wait until any of the pending messages/Exceptions/Logs are completly written into respective sources.
    /// Call this method before application is shutdown to make sure all logs are saved properly.
    /// </summary>
    public static void WaitForLogComplete()
    {
        Task.WaitAll(tasks.Values.ToArray());
    }