user25557558
user25557558

Reputation: 1

How can I pause a task in C#?

I am a beginner in the use of task in C#. I have implemented a file generation window in my application which generates 3 different files. I have implemented the file generation function on a single task, which runs in the background for generating the files, while the ui thread displays the status of files generated and logs regarding the generation.

I use a cancellation token for cancelling the task. I have an abort button, and when the user clicks on it, I call the cancel event of the token, and in the task, before starting the generation of a file, I call the ThrowIfCancellationRequested() of the token.

Now, I want to ask the user for confirmation first when he clicks on the abort button, and only cancel the task of he selects yes. The problem is that when I display the message, the task is running in the background, and I cannot pause it.

For now, I am doing the following: In task:

while(!_isTaskCancelled &&(!_isTaskPaused || !_isFilesGenerated)
{
    GenerateFile1();
    GenerateFile2();
    GenerateFile3();
    _isFileGenerated = _isFile1Generated && _isFile2Generated && _isFile3Generated;
    _isTaskPaused = isFileGenerated || _isTaskPaused;
}

In my generate functions:

try
{
    _cancellationTokenSource.Token.ThrowIfCancellationRequested();
    if(!_isTaskCancelled && !_isFile1Generated && !_isTaskPaused)
    {
        //Logic for generation
        _isFile1Generated = true;
    }
}
catch(Operation cancelled exception)
{
    _isFile1Generated = false;
}

In my abort button:

_isTaskPaused = true;
//Show message, store in isAborted
if(isAborted)
{
    _cancellationTokenSource.Cancel();
    _isTaskCancelled = true;
    //Close window
}
else
{
    _isTaskPaused = false;
}

Upvotes: 0

Views: 66

Answers (0)

Related Questions