The program has three timers, two timers of the type System.Windows.Forms.Timer for ticks update the information from the database and services, one of the type System.Timers.Timer sends requests to the service and writes data to the database. All of them create different threads, and when you try to close a form, an exception usually flies out that the thread has not yet worked. How, when trying to close a form, find out which threads besides the main one are still trying to work?

    1 answer 1

     Thread trThread = new Thread(()=>{}); trThead.Start(); trThread.IsAlive; 

    property indicating whether the stream has completed yet.

    Upd:

      internal class Program { #region Private Fields private static Timer timer = new Timer(DoCall, new object(), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); #endregion Private Fields #region Private Methods private static void DoCall(object state) { Thread.Sleep(2000); //вот тут я хватаю текущий поток за хвост и вывожу его Id. Console.WriteLine(Thread.CurrentThread.ManagedThreadId); //В вашем сценарии я бы в начале метода инкрементировал число запущенных "задач" а в конце декриментировал. И когда число будет = 0, значит все отработало. } private static void Main(string[] args) { Console.WriteLine("-"); Console.ReadKey(); timer.Dispose(); //тики закончились, ждем обнуления Count Console.ReadKey(); } #endregion Private Methods } 

    It should be understood that it is not guaranteed here, but the probability of getting that error has been removed to the minimum value. What is the essence. There is a tick, the time for which is definitely more than the time between ticks. we create a counter of "tasks", at the beginning of the method we do it ++, and on completion -. Further, when we want to exit Dispose on the timer and wait for the task counter to be reset. Then - exit.

    • What does this have to do with the threads that create timers? I do not manually create threads in timers, they create them themselves with every tick. - Dmitry Gvozd
    • That is, the code is executed in the Private Sub Timer2_Tick it is automatically executed in another thread. - Dmitriy Gvozd
    • It depends on what kind of timer. Then outline the task more specifically. Why is the timer for you the starting point? What synchronization primitives do not suit you? Those. Isolation flag IsOperationComplite = false. And then in the timer thread IsOperationComplite = true last support. Of course, everything is under lock-in. - Arheus
    • You can also get a timer thread. But this is a separate issue. - Arheus
    • the fact is that from the fact that you wrote me, I did not understand a single word ( - Dmitry Gvozd