我现在有以下代码。它正在工作,但picturesDownloaded
不会更新。在那5秒内,不调用sendData picturesDownloaded
得到另一个值。每次定时器运行时如何刷新?因此obj.ToString()
将是正确的价值。
在一个点picturesDownloaded
获取值“11”,但object obj
仍然具有值“0”。
public static volatile string picturesDownloaded = "0";
System.Threading.Timer timer = new System.Threading.Timer(sendData, picturesDownloaded, 1000 * 5, 1000 * 5);
public static void sendData(object obj)
{
WebClient wc = new WebClient();
string imageCountJson = wc.DownloadString("http://******/u.php?count=" + obj.ToString());
}
答案 0 :(得分:1)
试试这个:
public static volatile string picturesDownloaded = "0";
System.Threading.Timer timer = new System.Threading.Timer(sendData, new Func<string>(() => picturesDownloaded), 1000 * 5, 1000 * 5);
public static void sendData(object obj)
{
var value = ((Func<string>)obj)();
WebClient wc = new WebClient();
string imageCountJson = wc.DownloadString("http://******/u.php?count=" + value);
}
问题在于,在创建计时器时,会向构造函数传递对字符串"0"
的引用。更新picturesDownloaded
的值时,它不会更改传递给Timer
构造函数的对象的值。
这可以通过向Timer
构造函数提供匿名方法来解决,该构造函数可以检索更新的picturesDownloaded
值,然后在回调中调用该方法。