There is a method that implements file compression with the creation of an archive at the specified path:

public int Action(string typeJob,string fileInput, string fileOut) { if (FileExistCheck(fileInput, fileOut)) { using (FileStream sourceStream = new FileStream(fileInput, FileMode.Open)) { using (FileStream targetStream = File.Create(fileOut)) { switch (typeJob) { case "compress": using (GZipStream compressionStream = new GZipStream(targetStream, CompressionMode.Compress)) { sourceStream.CopyTo(compressionStream); return 0; } case "decompress": using (GZipStream decompressionStream = new GZipStream(sourceStream, CompressionMode.Decompress)) { try { decompressionStream.CopyTo(targetStream); return 0; } catch (InvalidDataException) { Console.WriteLine("Возможно путь к архиву указывает на файл иного типа"); File.Delete(fileOut); return 1; } } default: Console.WriteLine("Первый аргумент указан неверно"); Console.WriteLine("Следует выбрать compress или decompress"); File.Delete(fileOut); return 1; } } } } else return 1; } 

How can you stop this process by calling any method by pressing a key / key combination? I saw a lot of information about how to stop the eternal cycle, but I did not find about FileStream .

    1 answer 1

    Use the CancellationToken and CopyAsync() method:

    1. Change the signature of your method:

       public async Task<int> ActionAsync( string typeJob, string fileInput, string fileOut, CancellationToken token) 

      And in the body, use CopyToAsync() , passing it the token . Instead:

       sourceStream.CopyTo(compressionStream); 

      Write:

       await sourceStream.CopyToAsync(compressionStream, token).ConfigureAwait(false); 

      Similarly with decompressionStream .

    2. Somewhere higher, create a CancellationTokenSource and pass its token to your Action() method:

       var cts = new CancellationTokenSource(); ActionAsync(..., ..., ..., cts.Token); 
    3. At the moment you need (keystroke), cancel the task:

       cts.Cancel(); 

    PS The exception handling mechanism in C # was coined as a substitute for error codes. Therefore, I would advise to get rid of the return value of the method ( int ).

    • Besides tpl there is no way? - Garrus_En
    • 2
      @AntonLihatsky and you still need a second stream to read from the keyboard, regardless of the method you chose to interrupt the process. So why not tpl? - Pavel Mayorov
    • In fact, it turned out the Chinese diploma. inside the if (token.IsCansellationRequested) method and where it is not clear to configure this Requested. Outside? What advise you to read, it is generally not clear how to apply it to be honest - Garrus_En
    • where in the method body this construct is used here: await sourceStream.CopyToAsync (compressionStream, token) .ConfigureAwait (false); ?? - Garrus_En
    • one
      @ Anton Lihatsky where did you find if(token.IsCansellationRequested) in this answer? - Pavel Mayorov