 |
|
#ก็อปคลาสนี้ไปใส่ในคลาสของโปรเจคเรา
public static class TimedExecution<T> {
public static void Execute(Action action, TimeSpan timeout, Action onTimeout) {
Task task = Task.Run(action);
if (task.Wait(timeout)) {
// everything OK
} else {
onTimeout();
}
}
public static T Execute(Func<T> function, TimeSpan timeout, Func<T> onTimeout) {
Task<T> task = Task.Run(function);
if (task.Wait(timeout)) {
// the function returned in time
return task.Result;
} else {
// the function takes longer than the timeout
return onTimeout();
}
}
}
#สร้างฟังก์ชั่น DoSomething() ขึ้นมาในคลาสของโปรเจคเรา โดยใส่โค้ดที่จะใส่ timeout ไว้ในฟังก์ชั่นนี้
private bool DoSomething() {
// in the real world, the function should actually do something useful...
return true;
}
#ประกาศพารามิเตอร์ theFunction, timeout และ onTimeout ก็อปไปวางได้เลย โดย timeout ที่จะกำหนดก็คือ .FromSeconds(10);
Func<bool> theFunction = DoSomething;
TimeSpan timeout = TimeSpan.FromSeconds(10);
Func<bool> onTimeout = () => {
return false;
};
#วิธีเรียกใช้ฟังก์ชั่น แบบมี timeout
bool success = TimedExecution<bool>.Execute(theFunction, timeout, onTimeout);
|
 |
 |
 |
 |
Date :
2021-02-15 15:11:03 |
By :
ปาย KMITL#17 ชุมพร |
|
 |
 |
 |
 |
|
|
 |