C# System.Threading.Timer TimerCallback 委托带参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15930350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
System.Threading.Timer TimerCallback delegate with parameters?
提问by Crazywako
I need to pass the following int dldnow
to sendData static method / delegate.
我需要将以下内容传递int dldnow
给 sendData 静态方法/委托。
public int dldnow;
Timer timer = new Timer(new TimerCallback(sendData), null, 1000*30, 1000*30);
public static void sendData(object obj)
{
string imageCount = (string)dldnow;
string imageCountJson = wc.DownloadString("http://*********/u.php?count=" + imageCount);
}
采纳答案by alex
If you want to pass it once, use a second constructor parameter:
如果要传递一次,请使用第二个构造函数参数:
System.Threading.Timer(new TimerCallback(sendData), dldnow, 1000*30, 1000*30);
If you want to access it regularly, you can make a static volatile field:
如果你想定期访问它,你可以制作一个静态的 volatile 字段:
public static volatile int dldnow;
(volatile is need so that it would be always up to date when accessed from multiple threads)
(需要 volatile 以便从多个线程访问时它始终是最新的)