如何在Monotouch Button TouchDown事件处理程序中循环执行

时间:2011-05-04 09:05:36

标签: c# multithreading event-handling xamarin.ios uibutton

我在循环的每次迭代中尝试Thread.Sleep(1000),但infoLabel.Text在循环结束前不会更改。它在调用Thread.Sleep 3次后更改infoLabel.Text。 请指教。这是我的代码。

void Handle_Touchdown(object sender, EventArgs e)
{
 for(int i = 0; i < 10; ++i )
 {
    infoLabel.Text = i.ToStraing();
    Thread.Sleep(1000);
 }
}

1 个答案:

答案 0 :(得分:4)

你可能最好实现一个NSTimer并增加一个计数。可能的代码如下:

void Handle_Touchdown(object sender, EventArgs e)
{
    NSTimer timer;
    int counter = 0;

    timer = NSTimer.CreateRepeatingScheduledTimer(1, delegate{
        if (counter != 10)
        {
            counter++;
            infoLabel.Text = i.ToString();
        }
        else
            timer.Invalidate() // stop the timer
    });
}
相关问题