在不使用异步编程的情况下在c#中超时方法

在不使用异步编程的情况下在c#中超时方法,c#,asynchronous,timeout,C#,Asynchronous,Timeout,如果一个方法在不使用异步编程的情况下不返回结果,有没有办法在一段时间后超时 如果没有异步编程就做不到,请给我异步解决方案,但前者是首选 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){ //cod

如果一个方法在不使用异步编程的情况下不返回结果,有没有办法在一段时间后超时

如果没有异步编程就做不到,请给我异步解决方案,但前者是首选

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

}

我想你可以为循环发生的次数设置一个限制。我承认,我不会这样编程,但我也不会有这样的东西,不是异步的,所以不要判断

int loopnumber = 0;
int loopmax = 1000;
while (loopnumber <= 1000)
{
    //Do whatever
    loopnumber++;
}
int loopnumber=0;
int loopmax=1000;

while(loopnumber你可以这样做。从这里开始


显然,这不会打印
12345
。因为该方法超时。

您必须使用异步方法执行此操作。否则,您必须检查每行从方法返回的时间。可能重复,如果您有一个需要很长时间才能完成的循环,则可以检查每次迭代的超时。@M.kazemAkhgary“Thread t=new Thread(new ParameterizedThreadStart(function));”在main中,它给了我一个错误。我认为因为我的函数没有返回void。修复方法是什么?
    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";
    }