Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7910785
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T12:59:59+00:00 2026-06-03T12:59:59+00:00

All the service calls in my application are implemented as tasks.When ever a task

  • 0

All the service calls in my application are implemented as tasks.When ever a task is faulted ,I need to present the user with a dialog box to retry the last operation failed.If the user chooses retry the program should retry the task ,else the execution of the program should continue after logging the exception.Any one has got a high level idea on how to implement this functionality ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T13:00:00+00:00Added an answer on June 3, 2026 at 1:00 pm

    UPDATE 5/2017

    C# 6 exception filters make the catch clause a lot simpler :

        private static async Task<T> Retry<T>(Func<T> func, int retryCount)
        {
            while (true)
            {
                try
                {
                    var result = await Task.Run(func);
                    return result;
                }
                catch when (retryCount-- > 0){}
            }
        }
    

    and a recursive version:

        private static async Task<T> Retry<T>(Func<T> func, int retryCount)
        {
            try
            {
                var result = await Task.Run(func);
                return result;
            }
            catch when (retryCount-- > 0){}
            return await Retry(func, retryCount);
        }
    

    ORIGINAL

    There are many ways to code a Retry function: you can use recursion or task iteration. There was a discussion in the Greek .NET User group a while back on the different ways to do exactly this.
    If you are using F# you can also use Async constructs. Unfortunately, you can’t use the async/await constructs at least in the Async CTP, because the code generated by the compiler doesn’t like multiple awaits or possible rethrows in catch blocks.

    The recursive version is perhaps the simplest way to build a Retry in C#. The following version doesn’t use Unwrap and adds an optional delay before retries :

    private static Task<T> Retry<T>(Func<T> func, int retryCount, int delay, TaskCompletionSource<T> tcs = null)
        {
            if (tcs == null)
                tcs = new TaskCompletionSource<T>();
            Task.Factory.StartNew(func).ContinueWith(_original =>
            {
                if (_original.IsFaulted)
                {
                    if (retryCount == 0)
                        tcs.SetException(_original.Exception.InnerExceptions);
                    else
                        Task.Factory.StartNewDelayed(delay).ContinueWith(t =>
                        {
                            Retry(func, retryCount - 1, delay,tcs);
                        });
                }
                else
                    tcs.SetResult(_original.Result);
            });
            return tcs.Task;
        } 
    

    The StartNewDelayed function comes from the ParallelExtensionsExtras samples and uses a timer to trigger a TaskCompletionSource when the timeout occurs.

    The F# version is a lot simpler:

    let retry (asyncComputation : Async<'T>) (retryCount : int) : Async<'T> = 
    let rec retry' retryCount = 
        async {
            try
                let! result = asyncComputation  
                return result
            with exn ->
                if retryCount = 0 then
                    return raise exn
                else
                    return! retry' (retryCount - 1)
        }
    retry' retryCount
    

    Unfortunatley, it isn’t possible to write something similar in C# using async/await from the Async CTP because the compiler doesn’t like await statements inside a catch block. The following attempt also fails silenty, because the runtime doesn’t like encountering an await after an exception:

    private static async Task<T> Retry<T>(Func<T> func, int retryCount)
        {
            while (true)
            {
                try
                {
                    var result = await TaskEx.Run(func);
                    return result;
                }
                catch 
                {
                    if (retryCount == 0)
                        throw;
                    retryCount--;
                }
            }
        }
    

    As for asking the user, you can modify Retry to call a function that asks the user and returns a task through a TaskCompletionSource to trigger the next step when the user answers, eg:

     private static Task<bool> AskUser()
        {
            var tcs = new TaskCompletionSource<bool>();
            Task.Factory.StartNew(() =>
            {
                Console.WriteLine(@"Error Occured, continue? Y\N");
                var response = Console.ReadKey();
                tcs.SetResult(response.KeyChar=='y');
    
            });
            return tcs.Task;
        }
    
        private static Task<T> RetryAsk<T>(Func<T> func, int retryCount,  TaskCompletionSource<T> tcs = null)
        {
            if (tcs == null)
                tcs = new TaskCompletionSource<T>();
            Task.Factory.StartNew(func).ContinueWith(_original =>
            {
                if (_original.IsFaulted)
                {
                    if (retryCount == 0)
                        tcs.SetException(_original.Exception.InnerExceptions);
                    else
                        AskUser().ContinueWith(t =>
                        {
                            if (t.Result)
                                RetryAsk(func, retryCount - 1, tcs);
                        });
                }
                else
                    tcs.SetResult(_original.Result);
            });
            return tcs.Task;
        } 
    

    With all the continuations, you can see why an async version of Retry is so desirable.

    UPDATE:

    In Visual Studio 2012 Beta the following two versions work:

    A version with a while loop:

        private static async Task<T> Retry<T>(Func<T> func, int retryCount)
        {
            while (true)
            {
                try
                {
                    var result = await Task.Run(func);
                    return result;
                }
                catch
                {
                    if (retryCount == 0)
                        throw;
                    retryCount--;
                }
            }
        }
    

    and a recursive version:

        private static async Task<T> Retry<T>(Func<T> func, int retryCount)
        {
            try
            {
                var result = await Task.Run(func);
                return result;
            }
            catch
            {
                if (retryCount == 0)
                    throw;
            }
            return await Retry(func, --retryCount);
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to call web services from my WP7 client application for user login
I understand web service provides all SOAP,WSDL support, and it stands at a higher
I have some special parameters to all my wcf service methods that are handled
I'm writing a WCF service for the first time. The service and all of
Our database server is a SQL 2008 server. My colleagues all have XP service
Hi All I am currently having an issue calling a WCF service from a
All of this is pertaining to WebHttp binding, hosted in a custom Service Host
I'm calling a web service from a console app - all in C# on
Currently we got a web service up and running that handles all our C.R.U.D
I have written a Windows service to collect information from all of our SQL

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.