Click here to Skip to main content
15,886,786 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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using TimeoutFunctions;

namespace TimeoutFunctions.Sample
{
    public partial class TimeoutFunctionsSample : Form
    {
        public TimeoutFunctionsSample() {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e) {
            double timeoutInSeconds;
            if (!double.TryParse(txtSynchronousProcessTimeout.Text, out timeoutInSeconds))
                ShowError("Invalid value entered");
            else {
                ClearResults();
                TimeoutProcess process = new TimeoutProcess();
                WriteToResults("Starting process");
                bool status = process.Start(null, TimeSpan.FromSeconds(timeoutInSeconds), DoTimeoutProcess);
                if (!status)
                    WriteToResults("Timedout!");
            }
        }

        void ShowError(string msg) {
            MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        void DoTimeoutProcess(object arg) {
            for (int i = 0; i < 10; i++) {
                WriteToResults("Processing task {0}", i.ToString());
                Thread.Sleep(1000);
            }
        }
        readonly static object locker = new object();
        void WriteToResults(string msgFormat,params string[] args) {
            string msg = string.Format(msgFormat, args);
            this.BeginInvoke((MethodInvoker)delegate
            {
                lock(locker)
                    this.lstResults.Items.Add(msg);
            });
        }

        void ClearResults() {
            lstResults.Items.Clear();
        }

        TimeoutProcess asyncProcess = new TimeoutProcess();
        private void btnStartAsyncProcesses_Click(object sender, EventArgs e) {
            ClearResults();
            int processCount;
            double timeoutInSeconds;
            if (!int.TryParse(txtNoOfProcesses.Text, out processCount))
                ShowError("Invalid process count");
            else if (!double.TryParse(txtAsyncProcessTimeout.Text, out timeoutInSeconds))
                ShowError("Invalid async process timeout");
            else {
                asyncProcess.AsyncProcessCompleted += asyncProcess_AsyncProcessCompleted;
                for (int i = 0; i < processCount; i++) {
                    asyncProcess.StartAsync(string.Format("Process {0}",i), 
                        TimeSpan.FromSeconds(timeoutInSeconds), DoTimeoutProcess);
                }
            }
        }

        void asyncProcess_AsyncProcessCompleted(object sender, AsyncProcessEventArgs e) {
            string processName = (string)e.UserState;
            if (!e.HasProcessCompleted)
                WriteToResults(string.Format("{0} timedout", processName));
            WriteToResults("{0} async processes executing", asyncProcess.AsyncProcessCount.ToString());
        }
    }
}

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