C # WPF Threading How to Stop Properly

So, I have been playing with streams for the last couple of months, and although my result is as expected, I have the feeling that I am not doing it in the best way. I can't get a direct answer from those with whom I work on what is best, so I thought I would ask you guys.

Question: I'm going to try to make it so simple to bear with me. Say I have a form that has a start and stop button. A start button is triggered and an event that triggers a thread. Inside this thread, DoWorkit will call 3 methods. Method1 () prints to the console "A \ n" 10 times with a pause of 10 seconds. Method2 () and Method3 () are the same as another letter and different pause times between Console.WriteLine. Now, when you press the stop button, you want the answer to be immediate. I do not want to wait for the completion of these methods. How should I do it?

The way I do this passes my BackgroundWorker to each method and checks how worker.CancellationPending works

 public void Method1(BackgroundWorker worker)
    {
      for(int i = 0; i < 10 && !worker.CancellationPending; ++i)
      {
        Console.WriteLine("A");
        for(int j = 0; j < 100 && !worker.CancellationPending; ++i)
        {
          Thread.Sleep(100);
        }
      }
    }

, , , 1 , , DLL , keydown . , . , !worker.CancellationPending. CancellationPending. , , , . ?

+3
3

(return return), .

  public void Method1(Backgroundworker worker)
  {
     foreach (var discard in Method1Steps)
     {
        if (worker.CancelationPending)
           return;
     }
  }

  private IEnumerable<object> Method1Steps()
  {
     for (int i = 0; i < 10; ++i)
     {
        yield return null;
        Console.WriteLine("A");
        for (int j = 0; j < 100; ++i)
        {
           Thread.Sleep(100);
           yield return null;
        }
     }
  }

, try/catch/finally , .

+1

, . , . , . , , CancelationPending. , , , . - , - .

, CancelationPending , , , , " ".

CancelationPending. . , - . , , , .

, GUI, , , . , " " , . , , .

0

, , , , "Abort" ( ) (maybee not - , ). AFAIK, "" , - ! , , .. ...... .

Maybee "Stoppable", "Abort" "Stop" boolean? , , , 50 , - . - - . "", , . / cancelationToken, , Dan.

Actually, there are very few Windows APIs, etc., which are not so easily "untangled" or do not have asynchronous versions of "Ex", so they are mistaken .. "almost" can always be canceled, one way or another, for example, closing sockets, to force the socket to read, except by writing a temporary file, to force the notification of folder changes.

Rgds, Martin

0
source

All Articles