Task Execution with Cancel LogicNested if statements with 3 different parametersDetermining if current thread is executingProperly creating a Task to poll and dispatch child tasks with cancellation for eachGeneric Task Blocking QueueUsing Task<T> and actions for simple threading?BackgroundWorker vs TPL ProgressBar ExerciseReactiveUI and Rx background calculations with cancellationSecure client-side encryption of user contentTask Wrappers for starting operation only if previous task has finishedFilter data with optional parameters
Could a US political party gain complete control over the government by removing checks & balances?
Need help identifying/translating a plaque in Tangier, Morocco
Ideas for 3rd eye abilities
Why is my log file so massive? 22gb. I am running log backups
What is GPS' 19 year rollover and does it present a cybersecurity issue?
Lied on resume at previous job
Landlord wants to switch my lease to a "Land contract" to "get back at the city"
Extreme, but not acceptable situation and I can't start the work tomorrow morning
How to move the player while also allowing forces to affect it
Are white and non-white police officers equally likely to kill black suspects?
Is there a familial term for apples and pears?
Why airport relocation isn't done gradually?
Could Giant Ground Sloths have been a good pack animal for the ancient Mayans?
What to wear for invited talk in Canada
When blogging recipes, how can I support both readers who want the narrative/journey and ones who want the printer-friendly recipe?
How would photo IDs work for shapeshifters?
How is it possible for user's password to be changed after storage was encrypted? (on OS X, Android)
Unbreakable Formation vs. Cry of the Carnarium
New order #4: World
Domain expired, GoDaddy holds it and is asking more money
Is domain driven design an anti-SQL pattern?
Patience, young "Padovan"
Are objects structures and/or vice versa?
Typesetting a double Over Dot on top of a symbol
Task Execution with Cancel Logic
Nested if statements with 3 different parametersDetermining if current thread is executingProperly creating a Task to poll and dispatch child tasks with cancellation for eachGeneric Task Blocking QueueUsing Task<T> and actions for simple threading?BackgroundWorker vs TPL ProgressBar ExerciseReactiveUI and Rx background calculations with cancellationSecure client-side encryption of user contentTask Wrappers for starting operation only if previous task has finishedFilter data with optional parameters
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
In my assignment I am executing a long running NodeJs script from C# using EdgeJs. Since the script may take a long time to execute, I also want to provide user an option to Cancel the script execution in the middle. The cancellation status is maintained in the database and function IsScripteExecutionCancelled
returns true
if the user decides to cancel the execution.
To achieve this I am executing script in a background thread using Task.Run()
. The main thread contains a while
loop that runs until the ScriptExecution is over or is cancelled. I can solve this problem using native System.Threading.Thread
, but here I am trying to do it using TPL. Here is the code I have put in place:
bool executionStarted = false;
bool taskCompleted = false;
Result returnValue;
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task executionTask;
while (!(taskCompleted || token.IsCancellationRequested))
if (!executionStarted)
executionStarted = true;
executionTask = Task.Run(() =>
returnValue = ExecuteScript();
taskCompleted = true;
, token);
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
tokenSource.Cancel();
if(token.IsCancellationRequested)
returnValue= GetDefaultValueForCancellation();
return returnValue;
So, if IsScripteExecutionCancelled
returns true
the program will come out of the loop and will check if the script was cancelled, in which case I will return a default response. If the ExecuteScript completes my program will return the value returned by function ExecuteScript
. I am able to get the desired results using this implementation however I would like to get it validated.
Question: Is it the right way to address this problem?
c# task-parallel-library
$endgroup$
bumped to the homepage by Community♦ 12 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
add a comment |
$begingroup$
In my assignment I am executing a long running NodeJs script from C# using EdgeJs. Since the script may take a long time to execute, I also want to provide user an option to Cancel the script execution in the middle. The cancellation status is maintained in the database and function IsScripteExecutionCancelled
returns true
if the user decides to cancel the execution.
To achieve this I am executing script in a background thread using Task.Run()
. The main thread contains a while
loop that runs until the ScriptExecution is over or is cancelled. I can solve this problem using native System.Threading.Thread
, but here I am trying to do it using TPL. Here is the code I have put in place:
bool executionStarted = false;
bool taskCompleted = false;
Result returnValue;
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task executionTask;
while (!(taskCompleted || token.IsCancellationRequested))
if (!executionStarted)
executionStarted = true;
executionTask = Task.Run(() =>
returnValue = ExecuteScript();
taskCompleted = true;
, token);
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
tokenSource.Cancel();
if(token.IsCancellationRequested)
returnValue= GetDefaultValueForCancellation();
return returnValue;
So, if IsScripteExecutionCancelled
returns true
the program will come out of the loop and will check if the script was cancelled, in which case I will return a default response. If the ExecuteScript completes my program will return the value returned by function ExecuteScript
. I am able to get the desired results using this implementation however I would like to get it validated.
Question: Is it the right way to address this problem?
c# task-parallel-library
$endgroup$
bumped to the homepage by Community♦ 12 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
1
$begingroup$
You are going to have to provide more context. It is unclear what this code is suppose to be doing.
$endgroup$
– Nkosi
Mar 13 '18 at 11:33
$begingroup$
This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Questions should include a description of what the code does
$endgroup$
– Dannnno
Mar 13 '18 at 13:57
add a comment |
$begingroup$
In my assignment I am executing a long running NodeJs script from C# using EdgeJs. Since the script may take a long time to execute, I also want to provide user an option to Cancel the script execution in the middle. The cancellation status is maintained in the database and function IsScripteExecutionCancelled
returns true
if the user decides to cancel the execution.
To achieve this I am executing script in a background thread using Task.Run()
. The main thread contains a while
loop that runs until the ScriptExecution is over or is cancelled. I can solve this problem using native System.Threading.Thread
, but here I am trying to do it using TPL. Here is the code I have put in place:
bool executionStarted = false;
bool taskCompleted = false;
Result returnValue;
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task executionTask;
while (!(taskCompleted || token.IsCancellationRequested))
if (!executionStarted)
executionStarted = true;
executionTask = Task.Run(() =>
returnValue = ExecuteScript();
taskCompleted = true;
, token);
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
tokenSource.Cancel();
if(token.IsCancellationRequested)
returnValue= GetDefaultValueForCancellation();
return returnValue;
So, if IsScripteExecutionCancelled
returns true
the program will come out of the loop and will check if the script was cancelled, in which case I will return a default response. If the ExecuteScript completes my program will return the value returned by function ExecuteScript
. I am able to get the desired results using this implementation however I would like to get it validated.
Question: Is it the right way to address this problem?
c# task-parallel-library
$endgroup$
In my assignment I am executing a long running NodeJs script from C# using EdgeJs. Since the script may take a long time to execute, I also want to provide user an option to Cancel the script execution in the middle. The cancellation status is maintained in the database and function IsScripteExecutionCancelled
returns true
if the user decides to cancel the execution.
To achieve this I am executing script in a background thread using Task.Run()
. The main thread contains a while
loop that runs until the ScriptExecution is over or is cancelled. I can solve this problem using native System.Threading.Thread
, but here I am trying to do it using TPL. Here is the code I have put in place:
bool executionStarted = false;
bool taskCompleted = false;
Result returnValue;
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task executionTask;
while (!(taskCompleted || token.IsCancellationRequested))
if (!executionStarted)
executionStarted = true;
executionTask = Task.Run(() =>
returnValue = ExecuteScript();
taskCompleted = true;
, token);
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
tokenSource.Cancel();
if(token.IsCancellationRequested)
returnValue= GetDefaultValueForCancellation();
return returnValue;
So, if IsScripteExecutionCancelled
returns true
the program will come out of the loop and will check if the script was cancelled, in which case I will return a default response. If the ExecuteScript completes my program will return the value returned by function ExecuteScript
. I am able to get the desired results using this implementation however I would like to get it validated.
Question: Is it the right way to address this problem?
c# task-parallel-library
c# task-parallel-library
edited Mar 14 '18 at 16:48
Sᴀᴍ Onᴇᴌᴀ
10.3k62168
10.3k62168
asked Mar 13 '18 at 10:33
AashishAashish
1395
1395
bumped to the homepage by Community♦ 12 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
bumped to the homepage by Community♦ 12 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
1
$begingroup$
You are going to have to provide more context. It is unclear what this code is suppose to be doing.
$endgroup$
– Nkosi
Mar 13 '18 at 11:33
$begingroup$
This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Questions should include a description of what the code does
$endgroup$
– Dannnno
Mar 13 '18 at 13:57
add a comment |
1
$begingroup$
You are going to have to provide more context. It is unclear what this code is suppose to be doing.
$endgroup$
– Nkosi
Mar 13 '18 at 11:33
$begingroup$
This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Questions should include a description of what the code does
$endgroup$
– Dannnno
Mar 13 '18 at 13:57
1
1
$begingroup$
You are going to have to provide more context. It is unclear what this code is suppose to be doing.
$endgroup$
– Nkosi
Mar 13 '18 at 11:33
$begingroup$
You are going to have to provide more context. It is unclear what this code is suppose to be doing.
$endgroup$
– Nkosi
Mar 13 '18 at 11:33
$begingroup$
This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Questions should include a description of what the code does
$endgroup$
– Dannnno
Mar 13 '18 at 13:57
$begingroup$
This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Questions should include a description of what the code does
$endgroup$
– Dannnno
Mar 13 '18 at 13:57
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
Is there a better way of doing Task cancellation than the one I implemented
There's no task cancellation implemented here. By passing a token to Task.Run
you just make the returned task IsCanceled
equal to true in case it cancels itself (without, it gets IsFaulted
by the OperationCanceledException
). But you need (at least) to pass the token to DoSomeWork
, because that has to check the token and cancel itself.
Task cancellation works through cooperation of the to-be-canceled task and has nothing to do with Thread.Abort
.
$endgroup$
add a comment |
$begingroup$
you create a variable here and use it only once
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
tokenSource.Cancel();
I would just use the method in the if statement, like
if (IsScripteExecutionCancelled())
tokenSource.Cancel();
if you were going to use this value somewhere else and didn't want it evaluated again, then you could assign it to a variable, but then you need to keep in mind that calling the variable will not run the method.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f189478%2ftask-execution-with-cancel-logic%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Is there a better way of doing Task cancellation than the one I implemented
There's no task cancellation implemented here. By passing a token to Task.Run
you just make the returned task IsCanceled
equal to true in case it cancels itself (without, it gets IsFaulted
by the OperationCanceledException
). But you need (at least) to pass the token to DoSomeWork
, because that has to check the token and cancel itself.
Task cancellation works through cooperation of the to-be-canceled task and has nothing to do with Thread.Abort
.
$endgroup$
add a comment |
$begingroup$
Is there a better way of doing Task cancellation than the one I implemented
There's no task cancellation implemented here. By passing a token to Task.Run
you just make the returned task IsCanceled
equal to true in case it cancels itself (without, it gets IsFaulted
by the OperationCanceledException
). But you need (at least) to pass the token to DoSomeWork
, because that has to check the token and cancel itself.
Task cancellation works through cooperation of the to-be-canceled task and has nothing to do with Thread.Abort
.
$endgroup$
add a comment |
$begingroup$
Is there a better way of doing Task cancellation than the one I implemented
There's no task cancellation implemented here. By passing a token to Task.Run
you just make the returned task IsCanceled
equal to true in case it cancels itself (without, it gets IsFaulted
by the OperationCanceledException
). But you need (at least) to pass the token to DoSomeWork
, because that has to check the token and cancel itself.
Task cancellation works through cooperation of the to-be-canceled task and has nothing to do with Thread.Abort
.
$endgroup$
Is there a better way of doing Task cancellation than the one I implemented
There's no task cancellation implemented here. By passing a token to Task.Run
you just make the returned task IsCanceled
equal to true in case it cancels itself (without, it gets IsFaulted
by the OperationCanceledException
). But you need (at least) to pass the token to DoSomeWork
, because that has to check the token and cancel itself.
Task cancellation works through cooperation of the to-be-canceled task and has nothing to do with Thread.Abort
.
answered Mar 13 '18 at 15:36
HaukingerHaukinger
1194
1194
add a comment |
add a comment |
$begingroup$
you create a variable here and use it only once
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
tokenSource.Cancel();
I would just use the method in the if statement, like
if (IsScripteExecutionCancelled())
tokenSource.Cancel();
if you were going to use this value somewhere else and didn't want it evaluated again, then you could assign it to a variable, but then you need to keep in mind that calling the variable will not run the method.
$endgroup$
add a comment |
$begingroup$
you create a variable here and use it only once
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
tokenSource.Cancel();
I would just use the method in the if statement, like
if (IsScripteExecutionCancelled())
tokenSource.Cancel();
if you were going to use this value somewhere else and didn't want it evaluated again, then you could assign it to a variable, but then you need to keep in mind that calling the variable will not run the method.
$endgroup$
add a comment |
$begingroup$
you create a variable here and use it only once
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
tokenSource.Cancel();
I would just use the method in the if statement, like
if (IsScripteExecutionCancelled())
tokenSource.Cancel();
if you were going to use this value somewhere else and didn't want it evaluated again, then you could assign it to a variable, but then you need to keep in mind that calling the variable will not run the method.
$endgroup$
you create a variable here and use it only once
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
tokenSource.Cancel();
I would just use the method in the if statement, like
if (IsScripteExecutionCancelled())
tokenSource.Cancel();
if you were going to use this value somewhere else and didn't want it evaluated again, then you could assign it to a variable, but then you need to keep in mind that calling the variable will not run the method.
edited Mar 14 '18 at 18:59
answered Mar 14 '18 at 17:45
Malachi♦Malachi
25.6k774177
25.6k774177
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f189478%2ftask-execution-with-cancel-logic%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
$begingroup$
You are going to have to provide more context. It is unclear what this code is suppose to be doing.
$endgroup$
– Nkosi
Mar 13 '18 at 11:33
$begingroup$
This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Questions should include a description of what the code does
$endgroup$
– Dannnno
Mar 13 '18 at 13:57