0

I have the following code:

Thread validationThread = new Thread(DoAsyncValidationMethod);

validationThread.Start(threadParams);

bool isAborted = false;

int timeLeft = 5000;

// wait for thread terminates itself
if (!validationThread.Join(timeLeft))
{
    // timeout, abort thread
    validationThread.Abort();
    isAborted = true;
}

In other words, I'm doing some work that is supposed to complete in the time lapse specified (5000 ms). If completed or not, the thread approach taken will guarantee the code returns no later than 5 sec after it started.

Is there a way to accomplish this with the async/await pattern? or since the thread is just used for the trick, is there any other approach to take?

The more elegant and simple, the better. Thank you for the help.

1
  • Please never ever ever call Thread.Abort() unless you are trying to forcibly crash out of your app. Calling abort can corrupt the state of your .NET run-time resulting in the results of all other threads not being reliable. Jul 7, 2017 at 2:11

3 Answers 3

2

Here is a piece of code that I used in one of my projects.

Morever, have a look at Task.WhenAny(param Task[] task) method on MSDN. It returns the task which is completed.

var timeout = 5000;
var task = Task.Run(() => {
    Thread.Sleep(new Random().Next(3000, 7000));//Running time simulation!
    return "Say my name!";//Breaking Bad!
});
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // Task completed within timeout.
    // What if the task is faulted or canceled.
    // I did not supply a cancellation token but it can easily be added
    // We re-await the task so that any exceptions/cancellation is rethrown.
    await task;
}
else {
    // timeout/cancellation logic
}
13
  • Thank you Emrah, Pretty clever the second task parameter.
    – Alex
    Jul 7, 2017 at 2:17
  • @Alex, I hope it helps!. I am not sure of the performance of this code in a tight loop but I have used this without problems so far ('ω') Jul 7, 2017 at 2:20
  • @EmrahSüngü - new Random().Next(3000, 7000) in a tight loop might be a bad idea. Jul 7, 2017 at 2:22
  • @Enigmativity, It is an example to simulate a long running task. It is not a part of code. if (await Task.WhenAny(task, Task.Delay(timeout)) == task) { is where the magic begins :p Jul 7, 2017 at 2:23
  • 1
    @Alex, Consider marking it as answered if it helped you :) So it would help others who come across a similar problem Jul 7, 2017 at 2:40
2

Use a CancellationTokenSource. The source is a factory for CancellationTokens. You pass this token on to everyone you want to be able to cancel its processing in a neat way. When you want to cancel all processes that has a CancellationToken from the same CancellationTokenSource, just tell the CancellationTokenSource to send a cancel to all CancellationTokens it producted, thus cancelling all processes that have tokens from this source.

And the nice thing is, a CancellationTokenSource has a CancelAfter(some timeout).

Its good practice, to let your process starter give you the cancellationToken, so your process starter can decide which processes it wants to cancel in one call.

public async Task<MyResult> MyProcessAsync(CancellationToken cancellationToken, ...)
{
    // do something lengthy processing, without await, regularly check if Cancellation requested
    while (stillProcessing)
    {
        cancellationToken.ThrowIfCancellationRequested();
        ... // process
    }

    // do some processing with async-await:
    await myDbContext.SaveChangesAsync(cancellationToken);
}

Usage:

private async Task LengthyProcessing(...)
{
    CancellationTokenSource tokenSource = new CancellationTokenSource();
    tokenSource.CancelAfter(TimeSpan.FromSeconds(5));

    CancellationToken myCancellationToken = tokenSource.Token
    try
    {
       // Start one task, don't await yet:
       var myTask = await MyProcessAsync(myCancellationToken, ...)
       // during processing there will be regular check if cancellation requested
       // meanwhile, whenever myTask has to await, I can do some processing
       // I'll have to check for cancellation regularly also:

       while(...)
       {
           myCancellationToken.ThrowIfCancellationRequested();
           DoSomeProcessing();
           ...
       }

       MyResult result = await myTask;
       // if here, not cancelled. can use Result:
       ProcessResult(result);
    }
    catch (OperationCanceledException exc)
    {
        ProcessOperationCanceled();
    }
}

Note that only one CancelltionTokenSource is used. Whenever this source thinks that something should be cancelled, all threads that have tokens from this source get notified about the cancellationrequest.

Instead of using exception handling via CancellationToken.ThrowIfCancellationRequested() consider using bool CancellationToken.IsCancellationRequested.

MSDN how to cancel a task and its children

2
  • @Harald-thank you for this answer. This approach does not create a new thread, it all happens in the main thread, correct?
    – Alex
    Jul 7, 2017 at 14:35
  • never mind, I looked at the code in the link and realized a task would be used in the '... // process' section in your code.
    – Alex
    Jul 7, 2017 at 14:41
0

You can do this nicely with Microsoft's Reactive Framework (NuGet "System.Reactive"). Then you can do this:

IObservable<bool> query =
    Observable.Amb(
        Observable.Timer(TimeSpan.FromSeconds(5.0)).Select(_ => false),
        Observable.Start(() => DoAsyncValidationMethod()).Select(_ => true));

IDisposable subscription =
    query.Subscribe(flag =>
    {
        /* `true` succeeded, `false` timed out */
    });
6
  • Why the down-vote? This works just fine. What's the issue with this code? Jul 7, 2017 at 2:29
  • We started using Reactive solutions in our Unity projects. A different style of thinking style but it is fun! Jul 7, 2017 at 2:30
  • @EmrahSüngü - It's generally a lot more powerful than TPL. Jul 7, 2017 at 2:31
  • @Enigmativity, thank you for showing me a different way.
    – Alex
    Jul 7, 2017 at 2:38
  • @Enigmativity, even though I could not select your answer, I up-voted it since I wasn't aware of 'Reactive' and seems pretty interesting subject to learn more about.
    – Alex
    Jul 7, 2017 at 3:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.