0

Hi My function is so simple

private static bool IsUpdatedBefore(string filterName)
{
    try
    {
        var returnCollection = SomeFunction(filterName);

        if (returnCollection .Count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    catch (Exception ex)
    {
        Log.WriteLine(ex.ToString());
        return false;
    }
}

And I want to modify the code to return true if SomeFunction() takes more than an hour. But I have some problem

  1. I can't change SomeFunction()
  2. I can't use multi-thread structure

So In this case, how can I change this without modifying SomeFunction() and without using multithread?

akop
  • 5,981
  • 6
  • 24
  • 51
  • Does this answer your question? [Single threaded timer](https://stackoverflow.com/questions/5497466/single-threaded-timer) – dmedine Mar 11 '22 at 02:02
  • 1
    Do you have an XY problem? -> "if SomeFunction() takes more than an hour." – Mitch Wheat Mar 11 '22 at 02:19
  • 1
    `return DateTime.Now - dateTimeSavedBeforeYouStarted > new TimeSpan(1, 0, 0);` – Dour High Arch Mar 11 '22 at 03:50
  • 4
    There is no good solution to terminating the current thread, without modifying the function you wish to terminate. The best answer is to pass in a `CancellationToken` argument, which the method should then poll or pass to other methods. The second best answer is to fire a timer on another thread and deliberately crash your program. – Jeremy Lakeman Mar 11 '22 at 04:34
  • Can you wrap your function with another function and/or use `Task` api? Tasks are not inherently multi-threaded. – mcy Mar 15 '22 at 07:33

1 Answers1

0

I guess, that you want to cancel your method, when the hour is over. This is not possible without multithreading.

What is possible in that case is: You can save the timestamp, when you called the method. After the method has returned, you can check that timestamp (but be aware, it can take more than one hour).
The check is easy, as Dour High Arch already wrote in the comments.

private static bool IsUpdatedBefore(string filterName)
{
    var tStart = DateTime.Now;

    try
    {
        SomeFunction(filterName);
    }
    catch (Exception ex)
    {
       Log.WriteLine(ex.ToString());
       return false;
    }

    return DateTime.Now - tStart > new TimeSpan(1, 0, 0);
}

Edit

I've learned that the DateTime.Now is not the best for measure time. Thanks for comment, I dont saved your name. Is DateTime.Now the best way to measure a function's performance?

private static bool IsUpdatedBefore(string filterName)
{
    var stopwatch = Stopwatch.StartNew();

    try
    {
        SomeFunction(filterName);
    }
    catch (Exception ex)
    {
        Log.WriteLine(ex.ToString());
        return false;
    }

    sw.Stop();
    return sw.Elapsed > new Timespan(1, 0, 0);
}
akop
  • 5,981
  • 6
  • 24
  • 51