更好的方式来写重试逻辑没有转到

编程入门 行业动态 更新时间:2024-10-08 06:17:24
本文介绍了更好的方式来写重试逻辑没有转到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有更好的方式来写这个code,而无需使用 GOTO ?看来尴尬,但我想不出更好的办法。我需要能够执行一个重试尝试,但我不想复制任何code。

公共无效写入(绳体) {     布尔重试= FALSE; RetryPoint:     尝试     {         m_Outputfile.Write(体);         m_Outputfile.Flush();     }     赶上(例外)     {         如果(重试)             扔;         //尝试重新打开文件...         m_Outputfile =新的StreamWriter(m_Filepath,真正的);         重试= TRUE;         GOTO RetryPoint;     } }

解决方案

下面是我会用一个goto语句,而不是基本逻辑:

布尔成功= FALSE; INT试图= 2; 做 {     尝试     {         m_Outputfile =新的StreamWriter(m_Filepath,真正的);         m_Outputfile.Write(体);         m_Outputfile.Flush();         成功= TRUE;     }     赶上(例外)     {         tries--;     } } 而(!成功&安培;&安培;尝试大于0);

我只是说排名第尝试的逻辑,即使原来的问题没有任何。

Is there a better way to write this code without using goto? It seems awkward, but I can't think of a better way. I need to be able to perform one retry attempt, but I don't want to duplicate any code.

public void Write(string body) { bool retry = false; RetryPoint: try { m_Outputfile.Write(body); m_Outputfile.Flush(); } catch (Exception) { if( retry ) throw; // try to re-open the file... m_Outputfile = new StreamWriter(m_Filepath, true); retry = true; goto RetryPoint; } }

解决方案

Here is the basic logic that I would use instead of a goto statement:

bool succeeded = false; int tries = 2; do { try { m_Outputfile = new StreamWriter(m_Filepath, true); m_Outputfile.Write(body); m_Outputfile.Flush(); succeeded = true; } catch(Exception) { tries--; } } while (!succeeded && tries > 0);

I just added # of tries logic, even though the original question didn't have any.

更多推荐

更好的方式来写重试逻辑没有转到

本文发布于:2023-11-26 07:43:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633234.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转到   来写   重试   逻辑   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!