可能重复:
如何中止/取消 TPL 任务?
我有一个需要一些时间来执行的方法,因此我将结果作为回调返回。我的方法看起来像:
public static void DoWork( Action<object> onCompleteCallBack)
{
Task.Factory.StartNew( () => {
// Do work
onCompleteCallBack(someResult);
});
}
现在我希望能够停止执行该方法,以防用户不想等待。结果,这就是我所制定的:
static void Main ( string[] args )
{
var cancelMethod = DoWork( x =>
{
// method completed
Console.Write( x.ToString() );
});
Thread.Sleep( 5000 ); // some time passes
// then user decides to abort method
cancelMethod();
Console.Read();
}
static Action DoWork ( Action<object> onCompleteCallBack )
{
bool stopExecuting = false;
Task.Factory.StartNew( () =>
{
for ( var i = 0 ; i < 100000 ; i++ )
{
Thread.Sleep( 1 );
if ( stopExecuting )
{
onCompleteCallBack( "Method aborted!" );
return;
}
}
onCompleteCallBack( "Method completed successfully" );
} );
return () => { stopExecuting = true; };
}
什么是中止方法执行的更合适的方法?
编辑
感谢您的回答。我现在记得取消令牌的事情。象征性的东西很难记住。我想我会使用这种方法:
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 );
}
使用你们在这个问题的答案上建议的方法和这种方法会更好吗?我更喜欢这种方法。我认为它比取消令牌更容易阅读。
PS。我的 Visual Studio 放置了很多空间。随意格式化代码:)