0

我现在有以下代码。它可以正常工作,但picturesDownloaded不会更新。在这 5 秒内,未调用 sendDatapicturesDownloaded获取另一个值。每次计时器运行时如何刷新它?所以这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());
}
4

1 回答 1

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,然后在回调中调用该方法。

于 2013-04-10T16:57:05.633 回答