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

digitally_inspired

I am trying to create a logging library and things are good until the application shutdown is called. When application shutdown is called, any unfinished thread is killed and the specific log is lost.

As of now application exits even before the first 10 threads are complete. I want help on how to make the application wait until all threads created by library are done.

NOTE: Requirement I got are like this. Modifications should be only in the class 'Logging' since this will be a library and will be provided to end users. Handling of logging issues during app shutdown must be done within it. This is where I have trouble now.

Alternatively a solution like create an event in logging class to trigger all logging complete, and ask user to call app exit on that event is possible, but that I am trying to avoid since it adds that burden to end user and adds complexity for implementations. There is a possibility they may skip it, which I do not want. I am looking for a solution like user should do 'Logging.AddException(....)' and then forget about it.

Please help. Provide comments if you are not clear about the idea.

Here is the full code abstract which you can put into a console application. Note: Look for comments in CASE 1 and CASE 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.
    }
}

}

digitally_inspired

As of now I myself found a workaround.

    /// <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());
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

How to wait until all async calls are finished

From Dev

Make slideToggle wait until other div's slideUps have finished?

From Dev

How to wait for threads to finish their work, where threads created by clone in c?

From Dev

Wait until function is finished

From Dev

How to make python wait until the previous task is finished?

From Dev

How to wait until all tasks are finished before running code

From Dev

how to wait until a web request with HttpWebRequest is finished?

From Dev

Make the main thread wait until all threads finish

From Dev

How to wait until some jQuery methods are finished?

From Dev

How to wait until an animation is finished in Swift?

From Dev

How to wait until my batch file is finished

From Dev

How to wait until networking by Alamofire has finished?

From Dev

How to wait until all tasks finished without blocking UI thread?

From Dev

How to wait for all threads created within a method

From Dev

How do I make an Excel RefreshAll wait to close until finished?

From Dev

ExecutorService's shutdown() doesn't wait until all threads will be finished

From Dev

How to make Gulp wait until dest file is finished?

From Dev

How to wait until all NSOperations is finished?

From Dev

How to block new threads until all threads are created and started

From Dev

How to make python wait until the previous task is finished?

From Dev

How to make JS wait until protocol execution finished

From Dev

How to make the main wait for all threads to complete

From Dev

How to wait for a set of threads to finished or other event in C++

From Dev

Make Excel VBA wait until operation is finished

From Dev

Create threads in loop and wait until all threads finished/aborted

From Dev

Launch an application and wait until it has finished without blocking redraw

From Dev

How to get jQuery to wait until an animation is finished?

From Dev

How to make a python Script wait until download has finished

From Dev

Android - How to wait until a SnapshotListener has finished?

Related Related

  1. 1

    How to wait until all async calls are finished

  2. 2

    Make slideToggle wait until other div's slideUps have finished?

  3. 3

    How to wait for threads to finish their work, where threads created by clone in c?

  4. 4

    Wait until function is finished

  5. 5

    How to make python wait until the previous task is finished?

  6. 6

    How to wait until all tasks are finished before running code

  7. 7

    how to wait until a web request with HttpWebRequest is finished?

  8. 8

    Make the main thread wait until all threads finish

  9. 9

    How to wait until some jQuery methods are finished?

  10. 10

    How to wait until an animation is finished in Swift?

  11. 11

    How to wait until my batch file is finished

  12. 12

    How to wait until networking by Alamofire has finished?

  13. 13

    How to wait until all tasks finished without blocking UI thread?

  14. 14

    How to wait for all threads created within a method

  15. 15

    How do I make an Excel RefreshAll wait to close until finished?

  16. 16

    ExecutorService's shutdown() doesn't wait until all threads will be finished

  17. 17

    How to make Gulp wait until dest file is finished?

  18. 18

    How to wait until all NSOperations is finished?

  19. 19

    How to block new threads until all threads are created and started

  20. 20

    How to make python wait until the previous task is finished?

  21. 21

    How to make JS wait until protocol execution finished

  22. 22

    How to make the main wait for all threads to complete

  23. 23

    How to wait for a set of threads to finished or other event in C++

  24. 24

    Make Excel VBA wait until operation is finished

  25. 25

    Create threads in loop and wait until all threads finished/aborted

  26. 26

    Launch an application and wait until it has finished without blocking redraw

  27. 27

    How to get jQuery to wait until an animation is finished?

  28. 28

    How to make a python Script wait until download has finished

  29. 29

    Android - How to wait until a SnapshotListener has finished?

HotTag

Archive