gpt4 book ai didi

c# - 将 System.Threading.Timer 对象引用传递给它的回调函数

转载 作者:太空狗 更新时间:2023-10-30 00:24:40 24 4
gpt4 key购买 nike

是否可以将 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 constructor 中的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 将设置为计时器的引用。

关于c# - 将 System.Threading.Timer 对象引用传递给它的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22808868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com