c#不卡界面延迟 使用Thread可能会导致界面卡顿,可以通过使用BackgroundWorker和async/await模式、使用Delay函数、使用timer控件对要刷新的控件进行定时刷新、使用委托和线程安全的方法更新UI控件等方法解决

使用Delay函数

使用timer控件对要刷新的控件进行定时刷新

对刷新频率要求不高的时候,可以使用该方法。

 
//不卡界面延迟
public static void Delay(int mm)
{
DateTime current = DateTime.Now;
while (current.AddMilliseconds(mm) > DateTime.Now)
{
Application.DoEvents();
}
return;
}

使用委托和线程安全的方法更新UI控件

在开发软件时经常会需要更新界面上的某个控件来显示相关的信息,为了让程序执行中不出现界面卡死的现象,最好的方法就是多线程+委托来解决。

public delegate void DeleMyDelegate(); //定义委托
DeleMyDelegate deleMyDelegate; //声明委托

pictureBox1.Refresh();

public void Pic_Show()
{
    deleMyDelegate = new DeleMyDelegate(DeleMy); //绑定委托
}

private void button1_Click(object sender, EventArgs e)
{
    Thread myThread = new Thread(Pic_Show);
    myThread.Start();
}
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容