重复在C#中的函数,直到它不再抛出一个异常 [英] Repeating a function in C# until it no longer throws an exception
问题描述
我有一个调用SOAP接口,并获取数据数组后面的类。但是,如果此请求超时,它抛出一个异常。这是好事。不过,我想我的程序试图再次拨打这个电话。如果超时,我想它继续做这个调用,直到成功为止。我怎样才能做到这一点。
例如:
试
{
salesOrdersArray = MagServ.salesOrderList(sessID,过滤器);
}
抓
{
?善有善报这里给力上面一行代码来重新运行,直到成功为止。
}
您只需要永远循环下去
,而(真)
{
试
{
salesOrdersArray = MagServ.salesOrderList(sessID,过滤器);
中断; //退出循环。可以从该方法返回,在它做什么...
} $ b。根据
// $ B抓
{
//日志,我怀疑...
}
}
请注意,你应该几乎可以肯定的不其实永远循环下去。你几乎肯定应该有尝试的最大数量,大概只有捕获的具体的异常。醒目的所有的异常永远的可能是惨不忍睹......想象一下,如果 salesOrderList
(非常规的方法名,顺便说一句)抛出 ArgumentNullException
,因为你已经有了一个bug,过滤器
为空......你的真正的希望绑100%,你的CPU永远的?
I've got a class that calls a SOAP interface, and gets an array of data back. However, if this request times out, it throws an exception. This is good. However, I want my program to attempt to make this call again. If it times out, I'd like it to keep making this call until it succeeds. How can I accomplish this?
For example:
try
{
salesOrdersArray = MagServ.salesOrderList(sessID, filter);
}
catch
{
?? What Goes Here to FORCE the above line of code to rerun until it succeeds.
}
You just need to loop forever:
while (true)
{
try
{
salesOrdersArray = MagServ.salesOrderList(sessID, filter);
break; // Exit the loop. Could return from the method, depending
// on what it does...
}
catch
{
// Log, I suspect...
}
}
Note that you should almost certainly not actually loop forever. You should almost certainly have a maximum number of attempts, and probably only catch specific exceptions. Catching all exceptions forever could be appalling... imagine if salesOrderList
(unconventional method name, btw) throws ArgumentNullException
because you've got a bug and filter
is null... do you really want to tie up 100% of your CPU forever?
这篇关于重复在C#中的函数,直到它不再抛出一个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!