-
-
Save polatengin/28cfed0e33b4bbbfb3c4587039ea2863 to your computer and use it in GitHub Desktop.
This file contains 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
C# ile uzun süren method'ları kontrol altına alın |
This file contains 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
/// <summary> | |
/// Timeout süresinde tamamlanmayan method'u otomatik sonlandırır | |
/// </summary> | |
/// <param name="action">Çağırılacak method</param> | |
/// <param name="timeout">Milisaniye cinsinden zamanaşımı süresi</param> | |
/// <returns></returns> | |
public static bool Execute(Action action, int timeout) | |
{ | |
var tokenSource = new CancellationTokenSource(); | |
var token = tokenSource.Token; | |
var task = Task.Factory.StartNew(action, token); | |
if (!task.Wait(timeout, token)) | |
{ | |
tokenSource.Cancel(); | |
return false; | |
} | |
task.Dispose(); | |
return true; | |
} | |
/// <summary> | |
/// Timeout süresinde tamamlanmayan method'u otomatik sonlandırır | |
/// </summary> | |
/// <param name="action">Çağırılacak method</param> | |
/// <param name="timeout">Milisaniye cinsinden zamanaşımı süresi</param> | |
/// <returns></returns> | |
public static Tuple<bool, T> Execute<T>(Func<T> action, int timeout) | |
{ | |
var result = Tuple.Create(false, default(T)); | |
var tokenSource = new CancellationTokenSource(); | |
var token = tokenSource.Token; | |
var task = Task.Factory.StartNew(() => { result = Tuple.Create(true, action.Invoke()); }, token); | |
if (!task.Wait(timeout, token)) | |
{ | |
tokenSource.Cancel(); | |
} | |
task.Dispose(); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment