Is it possible to solve the timeout problem for calling a function in C #?

In my program, I call a method

xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); 


The problem I encountered: sometimes this function does not perform well in time.

Sometimes the compiler raises the timeout issue after a long trial. Which forces this part of the application to close. I want to avoid that.

So, if it exceeds a certain time, say 10 seconds, I need to call the method. Can I add some lines of code next to it that may meet the requirements?

+4
source share
1 answer

You need to call the method in the new Thread , and then call Join in the new thread with a timeout of 10 seconds.

For instance:

 public static bool RunWithTimeout(ThreadStart method, TimeSpan timeout, int maxTries) { while(maxTries > 0) { var thread = new Thread(method); thread.Start(); if (thread.Join(timeout)) return true; maxTries--; } return false; } if (!RunWithTimeout( delegate { xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); }, TimeSpan.FromSeconds(10), 5 //tries )) //Error! Waaah! 
+4
source

Source: https://habr.com/ru/post/1309769/


All Articles