Answered by:
How to cancel the operation performed in the Task

Question
-
I performed the task of an upload operation, and then need to stop the upload operation at any time, cancel the task but can not seem to cancel the upload operation, please advise, thank you very much.
class Program { private static TaskFactory taskFactory = new TaskFactory(); private static CancellationTokenSource cts = new CancellationTokenSource(); public static event Action CancelOnUploading = null; static void Main(string[] args) { Console.WriteLine("start uploading..."); taskFactory.StartNew(() => { while (true) { if(cts.IsCancellationRequested) { cts.Token.ThrowIfCancellationRequested(); CancelOnUploading = DoCancle; break; } Upload(); } }); Console.ReadKey(); cts.Cancel(); Console.WriteLine("Execute Cancel..."); Console.ReadKey(); } static void DoCancle() { Console.WriteLine("Cancel the task, stop uploading..."); } private static void Upload() { Console.WriteLine("login ..."); Thread.Sleep(1000); for (int i = 1; i <= 10; i++) { Console.WriteLine("The current upload the progress {0}%", i *10); Thread.Sleep(1000); } } }
Tuesday, March 26, 2013 9:42 AM
Answers
-
If you are uploading big amount of data in single call then cancelling the upload operation may not be possible. You should break your data in chunks and then upload it in multiple calls, this way you can abort the upload operation in between.
ViBi
Tuesday, March 26, 2013 10:43 AM -
Thank you for your help, I think I probably understand a little bit, Token passing to a class of judgment in the process of uploading, or corresponding upload upload function to add a cancellation and release method to Token.Register I started to think too simple into a misunderstanding
- Marked as answer by 大傻蛋啊 Wednesday, March 27, 2013 9:55 AM
Wednesday, March 27, 2013 2:46 AM
All replies
-
If you are uploading big amount of data in single call then cancelling the upload operation may not be possible. You should break your data in chunks and then upload it in multiple calls, this way you can abort the upload operation in between.
ViBi
Tuesday, March 26, 2013 10:43 AM -
Thank you for your help, I think I probably understand a little bit, Token passing to a class of judgment in the process of uploading, or corresponding upload upload function to add a cancellation and release method to Token.Register I started to think too simple into a misunderstanding
- Marked as answer by 大傻蛋啊 Wednesday, March 27, 2013 9:55 AM
Wednesday, March 27, 2013 2:46 AM