定时器回调委托在每次运行时都不会从参数获取刷新值

时间:2013-04-10 16:50:30

标签: c#

我现在有以下代码。它正在工作,但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());
}

1 个答案:

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