表单应用程序 C# 的无限 while 循环

Rav*_*pta 1 c# forms multithreading window

当表单应用程序启动时,我需要运行无限 while 循环。表单如下所示:

public Form1()
{
        InitializeComponent();
}
Run Code Online (Sandbox Code Playgroud)

现在我想运行另一个函数,该函数内部有一个无限循环,睡眠时间为一秒:

public void doProcess(){

    while(true){
         Thread.Sleep(1000);
         // other task
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?当我调用doProcess()构造函数时,它不显示表单。我尝试运行 while 循环 10 次迭代。表格只有在所有迭代完成后才显示。我不明白为什么会这样。

hol*_*see 5

简而言之,您正在通过这个无限循环阻塞 UI 线程。

异步运行它:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

while(true) 对于更新循环来说可能有点过多。我可以建议您使用计时器和/或利用取消令牌来急切地取消花费太长时间的请求,以免在高性能场景中更新 UI 并可能导致过时的结果。

例如

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();
    }
}
Run Code Online (Sandbox Code Playgroud)