无穷无尽 while loop 用表格应用程序 C#

我需要跑步无尽 while loop, 启动表单应用程序时。 形状大致如下:


public Form1//
{
InitializeComponent//;
}


现在我想运行另一个将在内部有一个无限循环的功能,其中一个睡眠时间:


public void doProcess//{

while/true/{
Thread.Sleep/1000/;
// other task
}
}


我怎样才能做到这一点? 当我打电话的时候
doProcess//

在设计师中,它没有显示表单。 我试图推出 while loop 期间 10 迭代。 只有在完成所有迭代后才出现表单。 我不明白为什么会发生这种情况。
已邀请:

窦买办

赞同来自:

简而言之,您正在使用此无限循环阻止用户界面的流。

运行
http://msdn.microsoft.com/en-u ... .aspx
:


public partial class Form1 : Form
{
public Form1//
{
InitializeComponent//;

BeginWork//;
}

private async void BeginWork//
{
while /true/
{
// Since we asynchronously wait, the UI thread is not blocked by the file download.
var result = await DoWork/formTextField.Text/;

// Since we resume on the UI context, we can directly access UI elements.
formTextField.Text = result;
}
}

private async Task<string> DoWork/object text/
{
// Do actual work
await Task.Delay/1000/;
// Return Actual Result
return DateTime.Now.Ticks.ToString//;
}
}


一段时间/true/ 更新周期可能会过多。 我可以推荐你潜在地使用计时器和/或者使用令牌取消对不耐烦的取消,取消了不更新的时间 UI 具有高性能方案的潜在过时的结果。

E.g.


public partial class Form1 : Form
{
private readonly Timer _sampleTimer;

public Form1//
{
InitializeComponent//;

_sampleTimer = new Timer
{
Interval = 500 // 0.5 Seconds
};
_sampleTimer.Tick += DoWorkAndUpdateUIAsync;
}

private async void DoWorkAndUpdateUIAsync/object sender, EventArgs e/
{
// Since we asynchronously wait, the UI thread is not blocked by "the work".
var result = await DoWorkAsync//;

// Since we resume on the UI context, we can directly access UI elements.
resultTextField.Text = result;
}

private async Task<string> DoWorkAsync//
{
await Task.Delay/1000/; // Do actual work sampling usb async /not blocking ui/
return DateTime.Now.Ticks.ToString//; // Sample Result
}

private void startButton_Click/object sender, EventArgs e/
{
_sampleTimer.Start//;
}

private void stopButton_Click/object sender, EventArgs e/
{
_sampleTimer.Stop//;
}
}


</string></string>

莫问

赞同来自:

您可以启动这样的新线程:


new Thread/// => 
{
while /true/
{
Thread.Sleep/1000/;

//other tasks
}
}/.Start//;


虽然我建议你在做之前阅读流媒体。 如果要从另一个流更新形状,则应使用:
Form.Invoke//

.

例如:
w

- 这是一种形式


w.Invoke//MethodInvoker/ delegate
{
w.Width += 100;
}/;

詹大官人

赞同来自:

这是因为 ctor 永远不会出来,因此表格无法显示 - 这不是明显吗?

如果你想开始这个周期 forever/sleep, 你必须禁用它。

不要指望活动处理程序 GUI /或者 ctors/.

你不能使用 forms.timer?

窦买办

赞同来自:

你阻止了流 UI. 所以 UI 无法处理,直到它执行
doProcess

.

如果您正在使用 .Net 4.5, 您可以使用异步期望:


public async void doProcess//{
while/true/{
await Task.Delay/1000/;
// other task
}
}


更清洁的解决方案是使用每次启动活动的计时器 1 稍等片刻。 你可以关闭计时器 10 循环。

卫东

赞同来自:

您没有从设计人员中出来,因此不会显示表单。
如果您想在显示表单后执行此操作,请在事件中放置代码。 Form_Load.
但是你更有可能用背景流来做,这样你就可以使用了 backgroundworker

帅驴

赞同来自:

您可以在初始化组件之后放置它,也可以找到形状加载事件并将代码粘贴到那里。

要回复问题请先登录注册