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, July 27, 2018 9:33:06 PM(UTC)
hong

Rank: Administration

Reputation:

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

How to timeout an async task / method

For asynchronous programming, we use Task Asynchronous Pattern or c# async / await methods. It's also easy to time the async task or method, for example
How to timeout a async task TcpSocketClient.ConnectAsync

Code:
var socketClient = new TcpSocketClient();
if (socketClient.ConnectAsync("remotehost", remotePort).Wait(1000))
{
    // connected
}
else
{
    // connection failure
}


To asynchronously wait for Task to complete with timeout
Code:
int timeout = 1000;
var task = MyOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) 
{
    // task completed within timeout
} 
else 
{ 
    // handle timeout
}


With cancellationToken:
Quote:
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
}


A TimeoutAfter async method:
Code:
public static async Task TimeoutAfter(this Task task, int timeout)
{
    if (task == await Task.WhenAny(task, Task.Delay(timeout))) 
        await task;
    else
        //handle time out
}


A TimeoutAfter<TResult> async method:
Quote:
Code:
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout)
    {

        using (var timeoutCancellationTokenSource = new CancellationTokenSource())
        {

            var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
            if (completedTask == task)
            {
                timeoutCancellationTokenSource.Cancel();
                //return task.Result;
                return await task;  // Very important in order to propagate exceptions

            }
            else
            {
                //handle time out
            }
        }
    }

Edited by user Wednesday, September 26, 2018 8:33:57 AM(UTC)  | Reason: Not specified

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.