Laden...

Klasse Timeout Manager

Erstellt von preli vor 16 Jahren Letzter Beitrag vor 16 Jahren 2.694 Views
preli Themenstarter:in
343 Beiträge seit 2007
vor 16 Jahren
Klasse Timeout Manager

Beschreibung:

Hallo allerseits!

Ich denke viele sind schon mal auf das Problem gestoßen: man will einen Codeteil ausführen, der maximal eine bestimmte Zeit lang brauchen darf.
Deshalb hab ich mir jetzt die Mühe gemacht und einen TimeoutManager programmiert, der genau dieses Problem löst. Am einfachsten ist das ganze wohl mit dem folgenden kleinen Beispiel gezeigt:


public void FunktionXY(...)
{
  //TimeoutManager erstellen
  TimeoutManager manager = new TimeoutManager();
  //welcher Code soll unter Beachtung der Zeitgrenze ausgeführt werden? (Funktion siehe weiter unten)
  manager.Function += new TimeoutDelegate(manager_Function);
  //TimeLimit in Millisekunden
  manager.Time = 3000;
  //Wenn die Zeit überschritten wird, wird eine TimeoutException geworfen
  try
  {
        manager.Start();
  }
  catch (TimeoutException)
  {
         MessageBox.Show("timeout");
  }
}

void manager_Function(object param)
{
     while (true)
     {
     }
}

Einen kleinen Haken hat die Sache allerdings: Der Code der auf Timeout überprüft wird, wird in einem seperaten Thread ausgeführt, also sind Zugriffe auf die Oberfläche nicht so einfach möglich.
Funktionieren tut es unter zwei Bedingungen:
1.) Die Property doEvents des TimeoutManagers muss true sein
2.) Beim Zugriff auf die Oberfläche muss mit Invoke gearbeitet werden

CODE der Klasse:


using System;
using System.Threading;
using System.Reflection;
using System.Windows.Forms;

namespace TimeOutManager
{

    public class TimeoutException: Exception { };

    public delegate void TimeoutDelegate(object param);

    public class TimeoutManager
    {

        #region attributes

        private Thread runThread = null;

        public event TimeoutDelegate Function = null;

        private object param = null;
        /// <summary>
        /// get/sets the parameter in the TimeoutFunction
        /// </summary>
        public object Param
        {
            get
            {
                return param;
            }
            set
            {
                param = value;
            }
        }

        private int time = 3000;
        /// <summary>
        /// Seconds till the TimeoutException is thrown
        /// </summary>
        public int Time
        {
            get
            {
                return time;
            }
            set
            {
                time = value;
                if (sleeptime == 50)
                    sleeptime = Math.Min(50, Math.Max(1, time / 10));
            }
        }


        private bool active;
        /// <summary>
        /// If the TimeoutManager is active or not (readonly).
        /// To set Active to true call the Start-Method
        /// </summary>
        public bool Active
        {
            get
            {
                return active;
            }
        }


        private int sleeptime = 50;
        /// <summary>
        /// Milliseconds to pause till to check the next time
        /// </summary>
        public int SleepTime
        {
            get
            {
                return sleeptime;
            }
            set
            {
                sleeptime = value;
            }
        }


        private bool doevents = false;
        /// <summary>
        /// if 'true' ApplicationEvents are handled during the Manager is active
        /// </summary>
        public bool doEvents
        {
            get
            {
                return doevents;
            }
            set
            {
                doevents = value;
            }
        }

        #endregion attributes

        #region constructor

        public TimeoutManager(TimeoutDelegate function, object param)
        {
            init(function, param);
        }

        private void init(TimeoutDelegate function, object param)
        {
            this.Function += function;
            this.param = param;
        }

        public TimeoutManager(TimeoutDelegate function)
        {
            init(function, null);
        }

        public TimeoutManager()
        {
        }

        public TimeoutManager(int Time, bool doEvents)
        {
            this.Time = Time;
            this.doevents = doEvents;
        }

        #endregion constructor

        /// <summary>
        /// starts the TimeoutManager
        /// </summary>
        public void Start()
        {
            DateTime startTime = DateTime.Now;
            runThread = new Thread(new ThreadStart(run));
            runThread.Start();
            active = true;
            while (runThread.IsAlive)
            {
                if (DateTime.Now.Subtract(startTime).TotalMilliseconds > time)
                {
                    runThread.Abort();
                    throw new TimeoutException();
                }
                else
                {
                    Thread.Sleep(sleeptime);
                    if (doEvents)
                        Application.DoEvents();
                }
            }
            active = false;
        }

        public void run()
        {
            if (Function != null)
            {
                Function(param);
            }
        }
    }
}

Schlagwörter: Timeout, TimeoutManager, Zeitlimit, Limit, Komponente

[- www.saftware.net -](http://www.saftware.net/)