I have a certain Func<bool> func
in C# (.NET Framework 4.8) in a WPF
application and want it to be executed. I'd like to have a method that takes this kind of Funcs
and returns a bool.
- It should run in the background and not block the UI thread. Probably I need
Task<bool>
for that? - If it takes longer than a certain timeout limit, it should be canceled and return
false
. - The program should wait for the task to be completed but not wait for the full time limit if it is already finished earlier.
- If it runs into an error, error message should be printed, the task should be canceled and the program should not crash or freeze.
Is there any sophisticated method that fullfills these requirements?
The solution can also use Task<bool>
instead of Func<bool>
if this a better solution.
It should be usable in a way similar to this:
public class Program
{
public static void Main(string[] args)
{
bool result = ExecuteFuncWithTimeLimit(3000, () =>
{
// some code here of a specific task / function
});
}
public static bool ExecuteFuncWithTimeLimit(int timeLimit_milliseconds, Func<bool> codeBlock)
{
// run func/task in background so GUI is not freezed
// if completed in time: return result of codeBlock
// if calceled due to time limit: return false
// if error occured: print error message and return false
}
}