为什么我的表单在visual basic中使用此代码时会冻结 [英] Why does my form freeze when using this code in visual basic

查看:65
本文介绍了为什么我的表单在visual basic中使用此代码时会冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码会冻结我在Visual Basic中的表单





why does this code freeze my form in visual basic


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click




    For i As Integer = 1 To 5

        System.Threading.Thread.Sleep(1000)
        TextBox1.Text = "/"
        System.Threading.Thread.Sleep(1000)
        TextBox1.Text = "\"
    Next




End Sub





我尝试了什么:



搜索互联网,但我没有找到enything



What I have tried:

searchign the internet but i did not find enything

推荐答案

因为你告诉UI线程在循环中进入两次睡眠状态。在事件处理程序退出之前,UI线程无法执行任何操作。由于UI线程改变了屏幕并处理了所有用户输入,因此表单将锁定,直到方法退出。
Because you are telling the UI thread to go to sleep twice inside a loop. And until the event handler exits, the UI thread can do nothing else. Since the UI thread is what changes the screen, and handles all user input, your form locks up until the method exits.


您可以找到许多有关'制作简单动画的教程使用visual basic ',只需使用 Google 。例如,请参阅如何:基本运动和VB.Net中的打字动画 - VB.NET教程| Dream.In.Code [ ^ ]。
You may find many tutorials on 'making a simple animation with visual basic', just using Google. See, for instance How To: Basic Movement And Typing Animations In VB.Net - VB.NET Tutorials | Dream.In.Code[^].


您可以使用Application.DoEvents为UI线程提供一个机会来赶上自己。< br $>


You can use Application.DoEvents to give the UI thread a chance to catch up with itself.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click




    For i As Integer = 1 To 5

        System.Threading.Thread.Sleep(1000)
        TextBox1.Text = "/"
        Application.DoEvents()
        System.Threading.Thread.Sleep(1000)
        TextBox1.Text = "\"
        Application.DoEvents()
    Next




End Sub





我会推荐你​​ DoEvents是邪恶的吗? [ ^ ]或si关于这是否是一种良好做法的不可避免的辩论。



I would refer you to Is DoEvents Evil?[^] or similar for the inevitable debate on whether that is good practice or not.


这篇关于为什么我的表单在visual basic中使用此代码时会冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆