0

Is there any way to time out a method after some time if it does not return result without using asynchronous programming?

If it cant be done without asynchronous programming ,Please give me the asynchronous solution but the former is preferred.

static void Main(string[] args){
string s=function(string filename); //want to time this out in 10 secs if does not return result
 }

 public string function(string filename){
 //code placed here to ftp a file and return as string
 //i know .net ftp library has its own timeouts, but i am not sure if they are that trust worthy

}
Raman
  • 216
  • 3
  • 15
  • 1
    you have to do it with asynchronous. otherwise you have to check for the time each line to return from method or not. possible duplicate http://stackoverflow.com/questions/2265412/set-timeout-to-an-operation , http://stackoverflow.com/questions/13513650/how-to-set-timeout-for-a-line-of-c-sharp-code – M.kazem Akhgary Sep 23 '15 at 20:06
  • if you have a loop which takes long time to complete you can check for timeout on each iteration. – M.kazem Akhgary Sep 23 '15 at 20:17
  • @M.kazemAkhgary when i do 'Thread t = new Thread(new ParameterizedThreadStart(function));' in main,it gives me an error. i think coz my function is not returning void. What would be the fix? – Raman Sep 23 '15 at 20:32

2 Answers2

0

I'd imagine you could just set a limit for the amount of times that the loop takes place for. I'll admit, I wouldn't program like this, but I also wouldn't have something like this not be asynchronous so don't judge.

int loopnumber = 0;
int loopmax = 1000;
while (loopnumber <= 1000)
{
    //Do whatever
    loopnumber++;
}
Sophie Coyne
  • 1,018
  • 7
  • 16
0

You can do it in this way. Taken from here How to set timeout for a line of c# code

    private static void Main(string[] args)
    {

        var tokenSource = new CancellationTokenSource();
        CancellationToken token = tokenSource.Token;
        int timeOut = 10000; // 10 s

        string output = ""; // the return of the function will be stored here

        var task = Task.Factory.StartNew(() => output = function(), token);

        if (!task.Wait(timeOut, token))
            Console.WriteLine("The Task timed out!");
        Console.WriteLine("Done" + output);
    }

    private static string function()
    {
        Task.Delay(20000).Wait(); // assume function takes 20 s

        return "12345";
    }

Obviously this will not print 12345. because the method timesout.

Community
  • 1
  • 1
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118