从另一个线程更新UI

从另一个线程更新UI

本文介绍了从另一个线程更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我们在一个应用程序上遇到问题,该应用程序正在TextBox的LostFocus上调用异步过程,然后异步过程需要能够在运行时更新主窗体UI(或从主窗体UI显示对话框).异步.

我们已经考虑过回调并使其具有真正的异步性,但是我们需要一切以正确的顺序执行,这适用于数据输入系统,其中数据输入的速度和准确性至关重要.

示例代码显示了我们正在尝试执行的操作,如果切换到BeginInvoke,则处理顺序不正确.

Hi,

We have an issue with an application where we are making a call to an asynchronous process on LostFocus of a TextBox, the asyncronous process then needs to be able to update the main form UI (or display a dialog from the main form UI) while running asynchronously.

We have thought about call backs and having it truely asynchronous but we need everything to execute in the correct order and this is for a data entry system where speed and accuracy of data entry is important.

Example code shows what we are trying to do and if you switch to BeginInvoke the order of processing is not correct.

<pre lang="vb">
Public Class Form1

    Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus

        '' execute the server subroutine
        Dim dlgt As New MethodInvoker(AddressOf Me.AsyncProcess)

        TextBox1.Text = "1"
        '' textbox should say 1

        '' call the server subroutine asynchronously, so the main thread is free
        Dim ar As IAsyncResult = dlgt.BeginInvoke(Nothing, Nothing)

        While ar.IsCompleted = False
            '' Application.DoEvents()
        End While
        '' textbox should now say 2

        TextBox1.Text = "3"
        '' textbox should now say 3
    End Sub

    Public Sub AsyncProcess()
        UpdateTextBox()
    End Sub

    Public Sub UpdateTextBox()
        If Me.InvokeRequired Then
            Me.Invoke(New MethodInvoker(AddressOf UpdateTextBox), "2")
        Else
            TextBox1.Text = "2"
        End If
    End Sub
End Class



有谁知道我们在忙于处理LostFocus事件时如何在主窗体线程上调用其他内容?

预先感谢.



Does anyone know how we can invoke something else on the main form thread while is is still busy processing the LostFocus event?

Thanks in advance.

推荐答案



这篇关于从另一个线程更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 12:57