Edit
Thanks for your answers. I remember now about the cancellation token thing. The token thing is hard to remember. I think I will use this approach:
static void Main ( string[ ] args ) { Action abortTask; DoWork( methodCompleted, out abortTask ); Thread.Sleep( 5000 ); // some time passes then user decides to abort method // cancel execution of method abortTask( ); Console.Read( ); } static void methodCompleted ( object msg ) { Console.Write( msg.ToString( ) ); } static void DoWork ( Action<object> onCompleteCallBack, out Action abortThisTask ) { bool stopExecuting = false; abortThisTask = ( ) => { stopExecuting = true; }; Task.Factory.StartNew( ( ) => { for ( var i = 0 ; i < 100000 ; i++ ) { Thread.Sleep( 1 ); if ( stopExecuting ) { onCompleteCallBack( "Method aborted!" ); return; } } onCompleteCallBack( "Method completed successfully" ); } ); } // Overloaded method static void DoWork ( Action<object> onCompleteCallBack ) { Action abortTask; DoWork( onCompleteCallBack ,out abortTask ); }
Will it be better to use the approaches you guys suggested on the answers to this question vs. This approach. I like this approach better. I think it is easier to read than the cancellation token one.
PS. My Visual Studio places a lot of spaces. Feel free to format the code :)