110,502
社区成员
发帖
与我相关
我的任务
分享
int count = 5;
private void CountDown()
{
while (true)
{
if (count == 0) { return; }
count -= 1;
lbl_Time.Text = count.ToString();
if (count == 0)
{
lbl_Time.Visible = false;
}
Thread.CurrentThread.Join(1000);
}
}
public partial class Form1 : Form
{
int count = 0;
System.Threading.Timer timerThr;
private delegate void SetTBMethodInvoke(object state);
public Form1()
{
InitializeComponent();
timerThr = new System.Threading.Timer(new TimerCallback(SetTB), null, Timeout.Infinite, 500);
}
public void SetTB(object value)
{
if (this.InvokeRequired)
{
this.Invoke(new SetTBMethodInvoke(SetTB), value);
}
else
{
count -= 1;
this.textBox1.Text = count.ToString();
if(count == 0)
{
}
}
}
private void btStart_Click(object sender, EventArgs e)
{
count = 6;
timerThr.Change(0, 1000);
}
private void btStop_Click(object sender, EventArgs e)
{
timerThr.Change(Timeout.Infinite, 1000);
}
}
public partial class Form2 : Form
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
// Fields...
private int _Count;
public int count
{
get { return _Count; }
set
{
_Count = value;
tokenSource.Cancel();
tokenSource = new CancellationTokenSource();
CountDown();
}
}
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.count = Convert.ToInt32(this.textBox1.Text);
}
void CountDown()
{
SynchronizationContext UIcontext = SynchronizationContext.Current;
var CancelToken= tokenSource.Token;
Task t = new Task(() =>
{
while (!CancelToken.IsCancellationRequested&&count>-1)
{
UIcontext.Post((p) => {
this.label1.Text = _Count.ToString();
_Count--;
}, null);
Thread.CurrentThread.Join(1000);
}
});
t.Start();
}
}