C#边循环边单击按钮
我正在微软visual studio 2012中用Winforms(C#)制作一个程序 我需要代码来做这件事C#边循环边单击按钮,c#,winforms,C#,Winforms,我正在微软visual studio 2012中用Winforms(C#)制作一个程序 我需要代码来做这件事 code code code Event for button click from user //Start while loop.. Do { code code code code code code } (!button not click again) 我知道很多人都在谈论多线程,但我认为我的水平太低,现在还不能使用它,所以如果我能避免的话,我会的 编辑:我最终使用了多线程
code code code
Event for button click from user
//Start while loop..
Do
{
code code code
code code code
} (!button not click again)
我知道很多人都在谈论多线程,但我认为我的水平太低,现在还不能使用它,所以如果我能避免的话,我会的
编辑:我最终使用了多线程,感谢所有的答案,它确实帮助了我很多,但当时多线程很难理解。你应该考虑将你的工作推进后台线程。这是因为主UI线程在
while
循环期间被停止,这意味着无法访问该按钮将其关闭。(我知道您说过要避免多线程,但现实情况是,在这种情况下需要使用它们)
最简单的方法可能是使用一个。它将为您处理许多线程生成方面的事情。您可以在后台工作程序的
DoWork
事件处理程序中执行while
循环。这将释放UI线程,这意味着该按钮将可单击,此时您可以设置停止循环的标志。我建议您看看线程,这是一个简单的解决方案,我不支持这种编程,但对于初学者来说,这是一种开始
code code code
Event for button click from user
//Start while loop..
Do
{
code code code
code code code
Application.DoEvents();
} (!button not click again)
Dispatcher
线程将被while
循环阻塞,因此它无法处理消息,这就是应用程序冻结的原因。您可以使用BackgroundWorker
或Task
类将逻辑从Dispatcher
中移出
public partial class Form1 : Form
{
// CancellationTokenSource will hold the CancellationToken struct
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
// Task will hold the logic
private readonly Task _task;
public Form1()
{
InitializeComponents();
// The task will be started on the ThreadPool off the Dispatcher thread
_task = Task.Factory.StartNew(() => EventLoop(_cts.Token), _cts.Token);
}
private void EventLoop(CancellationToken token)
{
while(!token.IsCancellationRequested)
{
// Do work
}
// This exception will be handled by the Task
// and will not cause the program to crash
token.ThrowIfCancellationRequested();
}
private void ButtonClick(object sender, EventArgs e)
{
_cts.Cancel();
}
}
见: