Question

I would like to run a function (funcA) and use another function (timerFunc) as a timer. If the running function (funcA) has run for 10 seconds, I would like to exit it using the timer function (timerFunc). Is this possible? Basically what I am trying to do:

void funcA() {
    // check event 1
    // check event 2
    // check event 3
    // time reaches max here! --exit--
    //check event 4
}

If not, what is the best way to handle such scenarios? I have considered using a stop-watch but I'm not sure if that is the best thing to do, mainly because I do not know after what event the timeout will be reached.

Was it helpful?

Solution

You could put all of the events into an array of Action or other type of delegate, then loop over the list and exit at the appropriate time.

Alternately, run all of the events in a background thread or Task or some other threading mechanism, and abort/exit the thread when you get to the appropriate time. A hard abort is a bad choice, as it can cause leaks, or deadlocks, but you could check CancellationToken or something else at appropriate times.

OTHER TIPS

Thread t = new Thread(LongProcess);
t.Start();
if (t.Join(10 * 1000) == false)
{
    t.Abort();
}
//You are here in at most 10 seconds


void LongProcess()
{
    try
    {
        Console.WriteLine("Start");
        Thread.Sleep(60 * 1000);
        Console.WriteLine("End");
    }
    catch (ThreadAbortException)
    {
        Console.WriteLine("Aborted");
    }
}

I would create a list and then very quickyl:

class Program
{
    static private bool stop = false;
    static void Main(string[] args)
    {
        Timer tim = new Timer(10000);
        tim.Elapsed += new ElapsedEventHandler(tim_Elapsed);
        tim.Start();

        int eventIndex = 0;
        foreach(Event ev in EventList)
        {
           //Check ev
            // see if the bool was set to true
            if (stop)
                break;
        }
    }

    static void tim_Elapsed(object sender, ElapsedEventArgs e)
    {
        stop = true;
    }
}

This should work for a simple scenario. If it's more complex, we might need more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top