本文介绍了更好的方式来写重试逻辑没有转到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有更好的方式来写这个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.
更多推荐
更好的方式来写重试逻辑没有转到
发布评论