【发布时间】:2014-04-02 10:40:53
【问题描述】:
是否可以将 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;
}
}
}
请给我一些想法或建议。 非常感谢,谢谢!
【问题讨论】: