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
}
}