Click here to Skip to main content
15,886,840 members
Articles / Programming Languages / XML

Timeout Functions

Rate me:
Please Sign up or sign in to vote.
4.95/5 (29 votes)
11 Dec 2008CPOL8 min read 76.6K   930   57  
This article explains about executing a function within a time limit. Also includes a helper class which helps to implement timeout functions easily. This article deals with running multiple timeout processes each with time limit.
namespace TimeoutFunctions
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using TimeoutFunctions.Workers;

    /// <summary>
    /// Executes methods within a timeout limit
    /// </summary>
    public sealed class TimeoutProcess
    {
        Dictionary<WorkerType, ITimeoutWorker> worker;

        /// <summary>
        /// Initializes a new instance of <see cref="TimeoutProcess"/>
        /// </summary>
        public TimeoutProcess() {
            worker = new Dictionary<WorkerType, ITimeoutWorker>(2);
            worker.Add(WorkerType.Normal, new TimeoutWorker());
            worker.Add(WorkerType.Asynchronous, new AsyncTimeoutWorker());
        }

        /// <summary>
        /// Fires when async process finishes or timedout
        /// </summary>
        public event EventHandler<AsyncProcessEventArgs> AsyncProcessCompleted {
            add {
                AsyncTimeoutWorker asynWorker = (AsyncTimeoutWorker)worker[WorkerType.Asynchronous];
                asynWorker.AsyncProcessCompleted += value;
            }
            remove {
                AsyncTimeoutWorker asynWorker = (AsyncTimeoutWorker)worker[WorkerType.Asynchronous];
                asynWorker.AsyncProcessCompleted -= value;
            }
        }

        /// <summary>
        /// Returns TRUE if any async processes are executing
        /// </summary>
        public bool IsAsyncProcessExecuting {
            get {
                AsyncTimeoutWorker asynWorker = (AsyncTimeoutWorker)worker[WorkerType.Asynchronous];
                return asynWorker.IsAsyncProcessExecuting; 
            }
        }

        /// <summary>
        /// Gets number of asynchronous processes currently executing
        /// </summary>
        public int AsyncProcessCount {
            get {
                AsyncTimeoutWorker asynWorker = (AsyncTimeoutWorker)worker[WorkerType.Asynchronous];
                return asynWorker.AsyncProcessCount; 
            }
        }

        /// <summary>
        /// Executes the specified method and time out when the specified time limit reached. This method blocks the calling thread.
        /// Return TRUE if the operation completed. FALSE if timedout
        /// </summary>
        /// <param name="userState">Custom object which will be passed to the executing method.</param>
        /// <param name="timeOut">Timeout limit</param>
        /// <param name="methodToExecute">Method to execute</param>
        /// <returns>TRUE if the operation completed. FALSE if timedout</returns>
        public bool Start(object userState, TimeSpan timeOut, WaitCallback methodToExecute) {

            if (methodToExecute == null)
                throw new ArgumentNullException("methodToExecute");
            return Start(WorkerType.Normal, new DataCarrier(userState,
                methodToExecute,
                timeOut));
        }

        /// <summary>
        /// Executes the supplied method in a non blocking fashion. 
        /// Raises <see cref="AsyncProcessCompleted"/> event when completed the process or timed out.
        /// </summary>
        /// <param name="userState">Custom user state</param>
        /// <param name="timeOut">Timeout value</param>
        /// <param name="methodToExecute">Method to execute</param>
        public void StartAsync(object userState, TimeSpan timeOut, WaitCallback methodToExecute) {
            if (methodToExecute == null)
                throw new ArgumentNullException("methodToExecute");

            // Starting the process
            Start(WorkerType.Asynchronous, new DataCarrier(userState, methodToExecute, timeOut));
        }

        /// <summary>
        /// Executes the supplied method in a non blocking fashion. 
        /// Raises <see cref="AsyncProcessCompleted"/> event when completed the process or timed out.
        /// </summary>
        /// <param name="userState">Custom user state</param>
        /// <param name="timeOut">Timeout value</param>
        /// <param name="methodToExecute">Method to execute</param>
        public void StartAsync(object userState, TimeSpan timeOut, WaitCallback methodToExecute,
            TimeSpan abortWaitTime) {
            if (methodToExecute == null)
                throw new ArgumentNullException("methodToExecute");

            // Starting the process
            Start(WorkerType.Asynchronous, new DataCarrier(userState, methodToExecute, timeOut, abortWaitTime));
        }

        bool Start(WorkerType workerType, DataCarrier dataCarrier) {
            return worker[workerType].Start(dataCarrier);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer ThoughtWorks
India India
Call me Navaneeth Some years ago--never mind how long precisely, I was doing programs with C and C++. When .NET came, I started with C#,ASP.NET and SQL Server.

Comments and Discussions