How to stop other threads in C#

Juan Dent 236 Reputation points
2022-08-02T21:18:03.487+00:00

I have a C# program with this line inside a loop:

Dispatcher.Invoke(updateProgressBar1, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, j });  

when I want to close the application by clicking the close button in the title bar, the application continues to run for a long time... how can I abort the work in the background?? How in general can I close all threads?

Thanks!
Juan

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

6 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,596 Reputation points Volunteer Moderator
    2022-08-02T21:56:20.817+00:00

    Have you considered using an asynchronous Task coupled with IProgress and a CancellationToken?

    See my code sample

    227413-figure1.png

    0 comments No comments

  2. Juan Dent 236 Reputation points
    2022-08-02T22:03:35.353+00:00

    First I need an answer to my question then I can refactor...


  3. Bruce (SqlWork.com) 82,061 Reputation points Volunteer Moderator
    2022-08-02T22:39:15.913+00:00

    Dispatcher does not use threads, it always the thread the Dispatcher is created on. you probably want to shutdown the dispatcher, so it no longer processes the queue.

    Dispatcher.InvokeShutdown();

    if you started a separate thread to run the Dispatcher, then you can kill that thread if you saved the thread handle.

    0 comments No comments

  4. Juan Dent 236 Reputation points
    2022-08-02T22:48:13.62+00:00

    Dispatcher.InvokeShutdown() does not stop the application!!

    0 comments No comments

  5. Bruce (SqlWork.com) 82,061 Reputation points Volunteer Moderator
    2022-08-03T02:10:15.213+00:00

    You don’t explain your app. How was dispatcher setup? Do you create any threads? How are you closing your app?

    The Dispatch.Shutdown() does not stop the current background process, just stops doing any more in the queue.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.