I have problem with .Cancel and .Wait in tasks. It takes a lot of memory and time.
Tasks:
using (CancellationTokenSource cancelSource = new CancellationTokenSource())
{
CancelEventArgs args = new CancelEventArgs(false);
Task task = Task.Factory.StartNew(() =>
{
try
{
action(args);
}
catch (Exception ex)
{
exception = ex;
}
}, cancelSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
bool success = task.Wait(maxRuntime);
if (!success)
{
cancelSource.Cancel();
return false;
}
}
In C# threading I use .Abort for aborting threads. Here in tasks I use .Cancel. But I think that .Cancel takes a lot of memory and time and it is not the same as .Abort in threads. How can I decrease memory when using
bool success = task.Wait(maxRuntime);
if (!success)
{
cancelSource.Cancel();
return false;
}
Threading example:
Thread workerThread = new Thread(threadStart);
workerThread.Start();
bool finished = workerThread.Join(timeout);
if (!finished)
workerThread.Abort();
return finished;
Canceling a task is fundamentally different from aborting a thread.
Aborting a thread will raise a
ThreadAbortExceptionin the thread you aborted. So even if the code that is executed inside the thread isn’t aware of this mechanism it gets aborted.Canceling a task on the other hand will not raise any exception. Instead, the task needs to check whether
CancellationToken.IsCancellationRequestedistrueand then actively throw anOperationCanceledExceptionexception. That means that the task will not respond to the cancellation request if the code executed by the task is not checking forIsCancellationRequested.See this MSDN page for more info.