abd*_*ahS 1 c# wpf user-interface sleep thread-sleep
我写了这个简单的程序等待2秒然后更新文本框:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
doSomething(i);
}
}
public void doSomething(int i)
{
System.Threading.Thread.Sleep(2000);
textBox1.Text += "this is the " + i + "th line\n";
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,UI会暂停,我无法对UI做任何事情.它不是动态的,所有必须在textbox1上显示的文本都会在运行结束时显示.
是否有任何替代System.Threading.Thread.Sleep?
您可以使用async/await而不阻止UI线程.
for (int i = 0; i < 10; i++)
{
await doSomething(i);
}
Run Code Online (Sandbox Code Playgroud)
public async Task doSomething(int i)
{
await Task.Delay(2000);
this.Text += "this is the " + i + "th line\n";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1138 次 |
| 最近记录: |