0

I would like to start a task by calling function StartTask() and stop the task by calling the function CloseStream(). The function StartTask() does seem to work but when I try to close it the program only outputs "a1" and is stuck on the "await t" line.

 public class server
 {
           public static string data = null;
           public static TcpClient Socket = new TcpClient();
           public static NetworkStream Stream = default(NetworkStream);
           public static CancellationTokenSource source = new CancellationTokenSource();
           public static bool logging = false;
           public static Task t = new Task(() => TaskAction(),source.Token);
           private static Control textbox;

           public static void StartTask()
           {
               t.Start();
           }
           public static async void CloseTask()
           {
               source.Cancel();
               try
               {
                   Console.WriteLine("a1");
                   await t;
                   Console.WriteLine("a2");
               }
               catch (OperationCanceledException e)
               {
                   Console.WriteLine($"{nameof(OperationCanceledException)} thrown with message: {e.Message}");
               }
               finally
               {
                   source.Dispose();
               }

               Socket.GetStream().Close();
               Socket.Close();
               Socket = new TcpClient();
               Stream = default(NetworkStream);
               Console.WriteLine("closed");

             }

           private static void TaskAction()
           {
                 //so something
           } 

}
  • Do you call `source.Token.ThrowIfCancellationRequested()` in your method `TaskAction()`? – SomeBody Oct 16 '20 at 12:31
  • Does this answer your question? [How to cancel a Task in await?](https://stackoverflow.com/questions/10134310/how-to-cancel-a-task-in-await) – Sinatr Oct 16 '20 at 12:32
  • 3
    AFAIK cancelling a Task will cause a `TaskCanceledException` and not a `OperationCanceledException` as library functions use `CancellationToken.ThrowIfCancellationRequested()`. Meaning the code in the `finally` scope will run but nothing afterwards as the uncaught exception will be bubbling upward. – Prime Oct 16 '20 at 12:42
  • having `static` objects for `Task` and `CancellationTokenSource` seems like a bad idea – Rufus L Oct 16 '20 at 14:59

0 Answers0