簡體   English   中英

將System.Threading.Timer對象引用傳遞給其回調函數

[英]Pass System.Threading.Timer object reference to its callback function

是否可以將System.Threading.Timer對象引用傳遞給它的回調函數,如下所示:

System.Threading.Timer myTimer = new System.Threading.Timer(new TimerCallback(DoSomething), myTimer, 2000, Timeout.Infinite);

因為在“DoSomething”方法中我想調用:

myTimer.Change(5000, Timeout.Infinite);

我將在下面粘貼草稿控制台應用程序。 想法是這樣的:我有計時器列表。 並且每個計時器都會發出一些請求,當它收到請求時,它會更改一些共享數據。 但是,我無法將定時器的引用傳遞給它的回調,也不能使用它的索引,因為它因某種原因(調查)變為“-1”。

using System;
using System.Collections.Generic;
using System.Threading;

namespace TimersInThreads
{
    class Program
    {
        public static int sharedDataInt;
        static private readonly object lockObject = new object();
        public static List<System.Threading.Timer> timers = new List<Timer>();

        static void Main(string[] args)
        {
            System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(DoSomething), timers.Count - 1, 2000, Timeout.Infinite);
            timers.Add(timer);

            System.Threading.Timer timer2 = new System.Threading.Timer(new TimerCallback(DoSomething), timers.Count - 1, 2000, Timeout.Infinite);
            timers.Add(timer2);

            System.Threading.Timer timer3 = new System.Threading.Timer(new TimerCallback(DoSomething), timers.Count - 1, 2000, Timeout.Infinite);
            timers.Add(timer3);

            //timer = new System.Threading.Timer(new TimerCallback(DoSomething), "Timer 1", 1000, Timeout.Infinite);
            //timer = new System.Threading.Timer(new TimerCallback(DoSomething), "Timer 2", 450, Timeout.Infinite);
            //timer = new System.Threading.Timer(new TimerCallback(DoSomething), "Timer 3", 1500, Timeout.Infinite);

            Console.ReadLine();

        }

        static void DoSomething(object timerIndex)
        {
            // Request
            // Get Response
            var x = getSomeNumberWithDelay();


            // Executes after Response is received
            lock (lockObject)
            {
                sharedDataInt++;
                Console.WriteLine("Timer" + (int)timerIndex + ", SHaredDataInt: " + sharedDataInt + "\t\t" + DateTime.Now.ToString("HH:mm:ss tt") + "." + DateTime.Now.Millisecond.ToString());
            }

            timers[(int)timerIndex].Change(5000, Timeout.Infinite);
        }

        static int getSomeNumberWithDelay()
        {
            Thread.Sleep(5000);
            return 3;
        }
    }
}

請給我一些想法或建議。 非常感謝,謝謝!

Timer構造函數中的state參數作為參數傳遞給TimerCallback - 這只是一個object因此可以處理任何事情,包括計時器引用本身。

所以

new System.Threading.Timer(new TimerCallback(DoSomething), myTimer, 2000, Timeout.Infinite);

完全可以接受。 在你的回調中你只需要將參數轉換為Timer例如

static void DoSomething(object state)
{
    ...
    var timer = (System.Threading.Timer)state;
}

再看一下你的問題,我看到你要做的是將計時器作為參數傳遞給它的構造函數(顯然這是不能完成的,因為它尚未正式聲明)。 您可以通過將計時器顯式傳遞給回調來解決此問題,例如

Timer t = null;
t = new Timer(delegate { DoSomething(t); }, null, 2000, Timeout.Infinite);

當回調被觸發時, t將設置為定時器的參考。

更換的每次出現timers.Count - 1timers.Count

System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(DoSomething), timers.Count, 2000, Timeout.Infinite);
timers.Add(timer);

將第一個計時器添加到列表時,沒有元素,因此timers.Count等於0

另一種方法是將特定計時器的實例作為回調的第二個參數而不是其索引。

我為此目的上了一堂課。 它提供TypedCallback,State和對Timer的引用。 該類維護一個引用列表並提供Disposal。

我沒有足夠的“積分”來發表評論,但也想指出在James的回答中,你需要確保保留對Timer的引用。 正如文檔所述,即使仍在運行,它們也會變成垃圾。

/// <summary>
/// Holds a list of references to Timers; and provides typed objects to reference the Timer and its
/// State from within a TypedCallback. Synchronized. Usage:
/// <code>
/// TypedStateTimers myTimers = new TypedStateTimers(3);
/// public void MyMethod() {
///     typedStateTimers.Create("Hello, from Timer", new TypedCallback<string>((sr) => {
///         System.Console.WriteLine(sr.State); // "Hello, from Timer"
///         sr.Dispose(); // Invoke the StateRef method to ensure references are released
///     })).Start(1500, Timeout.Infinite);
/// }
/// </code>
/// </summary>
public class TypedStateTimers
{
    /// <summary>
    /// A typed delegate used as the callback when Timers are created.
    /// </summary>
    public delegate void TypedCallback<T>(StateRef<T> state);


    /// <summary>
    /// Wraps a Timer and State object to be used from within a TypedCallback.
    /// </summary>
    public class StateRef<T> : IDisposable
    {
        /// <summary>The state passed into TypedStateTimers.Create. May be null.</summary>
        public T State { get; internal set; }

        /// <summary>The Timer: initially not started. Not null.</summary>
        public System.Threading.Timer Timer { get; internal set; }

        /// <summary>The TypedStateTimers instance that created this object. Not null.</summary>
        public TypedStateTimers Parent { get; internal set; }


        /// <summary>
        /// A reference to this object is retained; and then Timer's dueTime and period are changed
        /// to the arguments.
        /// </summary>
        public void Start(int dueTime, int period) {
            lock (Parent.Treelock) {
                Parent.Add(this);
                Timer.Change(dueTime, period);
            }
        }

        /// <summary>Disposes the Timer; and releases references to Timer, State, and this object.</summary>
        public void Dispose() {
            lock (Parent.Treelock) {
                if (Timer == null) return;
                Timer.Dispose();
                Timer = null;
                State = default(T);
                Parent.Remove(this);
            }
        }
    }


    internal readonly object Treelock = new object();
    private readonly List<IDisposable> stateRefs;


    /// <summary>
    /// Constructs an instance with an internal List of StateRef references set to the initialCapacity.
    /// </summary>
    public TypedStateTimers(int initialCapacity) {
        stateRefs = new List<IDisposable>(initialCapacity);
    }


    /// <summary>Invoked by the StateRef to add it to our List. Not Synchronized.</summary>
    internal void Add<T>(StateRef<T> stateRef) {
        stateRefs.Add(stateRef);
    }

    /// <summary>Invoked by the StateRef to remove it from our List. Not synchronized.</summary>
    internal void Remove<T>(StateRef<T> stateRef) {
        stateRefs.Remove(stateRef);
    }

    /// <summary>
    /// Creates a new StateRef object containing state and a new Timer that will use the callback and state.
    /// The Timer will initially not be started. The returned object will be passed into the callback as its
    /// argument. Start the Timer by invoking StateRef.Start. Dispose the Timer, and release references to it,
    /// state, and the StateRef by invoking StateRef.Dispose. No references are held on the Timer, state or
    /// the StateRef until StateRef.Start is invoked. See the class documentation for a usage example.
    /// </summary>
    public StateRef<T> Create<T>(T state, TypedCallback<T> callback) {
        StateRef<T> stateRef = new StateRef<T>();
        stateRef.Parent = this;
        stateRef.State = state;
        stateRef.Timer = new System.Threading.Timer(
                new TimerCallback((s) => { callback.Invoke((StateRef<T>) s); }),
                stateRef, Timeout.Infinite, Timeout.Infinite);
        return stateRef;
    }

    /// <summary>Disposes all current StateRef instances; and releases all references.</summary>
    public void DisposeAll() {
        lock (Treelock) {
            IDisposable[] refs = stateRefs.ToArray();
            foreach (IDisposable stateRef in refs) stateRef.Dispose();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM