在C#中制作一个简单的计时器 [英] making a simple timer in C#
问题描述
我还是c#的新手,我不知道如何每十秒调用一次updateTime()
I'm still new to c# and i dont how to invoke the method updateTime() every ten seconds
public class MainActivity : Activity
{
TextView timerViewer;
private CountDownTimer countDownTimer;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
timerViewer = FindViewById<TextView> (Resource.Id.textView1);
// i need to invoke this every ten seconds
updateTimeinViewer();
}
protected void updateTimeinViewer(){
// changes the textViewer
}
}
如果有一种方法可以创建一个新的线程或类似的东西,我将寻求帮助.
if there's a way to create a new Thread or something similar, i would be please to get some help.
我正在使用Xamarin Studio
I'm using Xamarin Studio
推荐答案
1 - One usual way to do that in C# is to use a System.Threading.Timer
, like so:
int count = 1;
TextView timerViewer;
private System.Threading.Timer timer;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
timerViewer = FindViewById<TextView>(Resource.Id.textView1);
timer = new Timer(x => UpdateView(), null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
}
private void UpdateView()
{
this.RunOnUiThread(() => timerViewer.Text = string.Format("{0} ticks!", count++));
}
请注意,在访问UI元素时,您需要使用 Activity.RunOnUiThread()
以避免跨线程冲突.
Notice that you need to use Activity.RunOnUiThread()
in order to avoid cross-thread violations when accessing UI elements.
2 - Another, cleaner approach is to make use of C#'s Language-level support for asynchrony, which removes the need to manually marshal back and forth to the UI thread:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
timerViewer = FindViewById<TextView>(Resource.Id.textView1);
RunUpdateLoop();
}
private async void RunUpdateLoop()
{
int count = 1;
while (true)
{
await Task.Delay(1000);
timerViewer .Text = string.Format("{0} ticks!", count++);
}
}
请注意,此处不需要 Activity.RunOnUiThread()
.C#编译器会自动发现这一点.
Notice there's no need for Activity.RunOnUiThread()
here. the C# compiler figures that out automatically.
这篇关于在C#中制作一个简单的计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!