More Group Sites
Education Books
School Rankings
Jobless Net
Better Home
Enviro++
更好教育论坛


Help | Subscribe/Unsubscribe | Rules | Other Group Sites: Better Education | Better Education Forum
Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Share
Options
View
Go to last post Go to first unread
hong  
#1 Posted : Friday, 26 October 2018 8:47:01 PM(UTC)
hong

Rank: Administration

Reputation:

Groups: AcademicCoachingSchool, admin, Administration, BookSeller, CatholicSchool, CoachingAdult, CoachingProfessional, CoachingSports, ExtraCurriculumCoaching, IndependentSchool, Moderator, MusicTeacher, PrivateSchool, PublicSchool, SelectiveSchool, tutor
Joined: 23/11/2008(UTC)
Posts: 519

Asynchronously wait for Task<T> to complete with timeout - Non blocking timeout instead of task.wait

For async programming, blocking Task.Wait should be avoided. Then how can we achieve time out with an async method / task? There are several ways.

1. Cancel async tasks after a period of time using using the CancellationTokenSource.CancelAfter
https://msdn.microsoft.c...us/library/jj155760.aspx
Code:
private async void startButton_Click(object sender, RoutedEventArgs e)
{
    // Instantiate the CancellationTokenSource.
    cts = new CancellationTokenSource();

    resultsTextBox.Clear();

    try
    {
        // ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You
        // can adjust the time.)
        cts.CancelAfter(2500);

        await AccessTheWebAsync(cts.Token);
        resultsTextBox.Text += "\r\nDownloads succeeded.\r\n";
    }
    catch (OperationCanceledException)
    {
        resultsTextBox.Text += "\r\nDownloads canceled.\r\n";
    }
    catch (Exception)
    {
        resultsTextBox.Text += "\r\nDownloads failed.\r\n";
    }

    cts = null;
}


In essence:
Code:
var cts = new CancellationTokenSource();
try
{
    cts.CancelAfter(timeout);
    await Client.PerformCheckAsync(request, cts.Token);
}
catch (OperationCanceledException)
{
    //handle cancellation
}
catch (Exception)
{
    //handle exception
}


2. time out and an additional cancellation token - multiple cancellation methods. Note that the cancellationToken is optional.
Code:
int timeout = 1000;
var task = SomeOperationAsync(cancellationToken);
if (await Task.WhenAny(task, Task.Delay(timeout, cancellationToken)) == task)
{
    // Task completed within timeout.
    // Consider that the task may have faulted or been canceled.
    // We re-await the task so that any exceptions/cancellation is rethrown.
    await task;

}
else
{
    // timeout/cancellation logic
}


3. TaskWithTimeoutWrapper
https://gist.github.com/...ff56a15845377c64ed9f9181
var result = await new TaskWithTimeoutWrapper().RunWithCustomTimeoutAsync(timeout, async () => await SomeOperationAsync(cts), cts);
Like 2 above, time out and an additional cancellation token cts - multiple cancellation methods. Note that the cancellationToken cts is optional.
Sponsor
Rss Feed  Atom Feed
Users browsing this topic
Guest
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.