System.Threading.Timer TimerCallback委托与参数?

Jon*_*nen 1 c# timer

我需要将以下内容传递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);
}
Run Code Online (Sandbox Code Playgroud)

ale*_*lex 7

如果要传递一次,请使用第二个构造函数参数:

System.Threading.Timer(new TimerCallback(sendData), dldnow, 1000*30, 1000*30);
Run Code Online (Sandbox Code Playgroud)

如果要定期访问它,可以创建一个静态volatile字段:

public static volatile int dldnow;
Run Code Online (Sandbox Code Playgroud)

(需要使用volatile,以便从多个线程访问时始终保持最新状态)