Created
January 10, 2017 12:52
-
-
Save enif-lee/ded84bb1872e1d7c405f0b92f16be03c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Samples | |
{ | |
/// <summary> | |
/// 동기적으로 재시도를 해야하는 경우 사용되는 retry 함수입니다. | |
/// </summary> | |
public class Retry | |
{ | |
/// <summary> | |
/// 반환값이 R타입인 재시도 함수입니다. | |
/// </summary> | |
/// <typeparam name="R">반환 타입</typeparam> | |
/// <param name="function">실행할 함수</param> | |
/// <param name="retryCount">재시도 횟수, 기본값은 1</param> | |
/// <param name="exception">예외 핸들러, 기본값은 null</param> | |
/// <param name="fail">retry 실패시 핸들러, 기본값은 null</param> | |
/// <returns>function의 실행 결과</returns> | |
public static R Do<R>( | |
Func<R> function, | |
int retryCount = 1, | |
Action<Exception> exception = null, | |
Action fail = null) | |
{ | |
R result = default(R); | |
Retry.Do( | |
action: () => | |
{ | |
result = function(); | |
}, | |
retryCount: retryCount, | |
exception: exception, | |
fail: fail); | |
return result; | |
} | |
/// <summary> | |
/// 반환값이 없는 재시도 함수입니다. | |
/// </summary> | |
/// <param name="action">시도할 반환값이 없는 action</param> | |
/// <param name="retryCount">재시도할 횟수, 기본 값은 1</param> | |
/// <param name="exception">exception 발생시 핸들러, 기본값은 null</param> | |
/// <param name="fail">retry 실패시 핸들러, 기본값은 null</param> | |
public static void Do( | |
Action action, | |
int retryCount = 1, | |
Action<Exception> exception = null, | |
Action fail = null) | |
{ | |
int failedCount = 0; | |
for (int retry = 0; retry < retryCount; retry++) | |
{ | |
try | |
{ | |
action(); | |
break; | |
} | |
catch (Exception e) | |
{ | |
if (exception != null) | |
{ | |
failedCount++; | |
exception(e); | |
} | |
} | |
} | |
if (failedCount == retryCount) | |
{ | |
if (fail != null) | |
{ | |
fail(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment