我仍然没有得到代表们代表

2023-09-04 02:00:54 作者:黄泉路上唱咆哮!

时不宜使用代表,以帮助一些异步的情况下?我尝试以下,但我的UI仍然挂起。当在地球上使用代表?

 公共类Form1中
    私人代表小组testDelegate()

    私人小组的button1_Click(BYVAL发件人为System.Object的,BYVAL E上_
 System.EventArgs)把手Button1.Click

        昏暗d为1 testDelegate =新testDelegate(AddressOf添加)
        d.Invoke()

    结束小组

    私人小组的Add()
        对于我作为整数= 0〜10000
            TextBox1.Text = I + 1
        下一个
    结束小组
末级
 

解决方案

这是一种讽刺,但大家最喜欢的答案(使用的BeginInvoke)其实也不是正确的。委托目标的方法将在一个线程池线程上执行。你不允许触摸的线程不是创建它们的线程其他控件,几乎都是程序的主线程。

如果您在使用.NET Framework 2.0版,并在调试器试试吧,环路将立即与IllegalOperationException终止。要纠正这一点,你将不得不使用Control.BeginInvoke()。从委托的的BeginInvoke()方法,顺便说一句。

一个完全不同的动物 毛不易,是个好文案

现在,这里的讽刺,你的循环,现在将派遣万委托调用请求UI线程。它会花几秒钟的执行它们,没有得到周围做任何实际工作。像派遣文本框的Paint事件。或者响应任何用户输入。你其实很多比以前更糟。

我怀疑这有助于解释很多代表。也许你可以挑一个更好的例子,一些不尝试更新控制。

Isn't the use of delegates to help with some asynchronous cases? I tried the following but my UI still hangs. When on earth do you use delegates?

       Public Class Form1
    Private Delegate Sub testDelegate()

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

        Dim d As testDelegate = New testDelegate(AddressOf Add)
        d.Invoke()

    End Sub

    Private Sub Add()
        For i As Integer = 0 To 10000
            TextBox1.Text = i + 1
        Next
    End Sub
End Class

解决方案

It's kind of ironic, but everybody's favorite answer (use BeginInvoke) is not in fact correct. The delegate target method will execute on a threadpool thread. You are not allowed to touch controls on a thread other than the thread that created them, almost always the program's main thread.

If you try it using the .NET framework version 2.0 and up in the debugger, the loop will immediately terminate with an IllegalOperationException. To correct that, you'll have to use Control.BeginInvoke(). A completely different animal from the delegate's BeginInvoke() method btw.

Now here's the irony, your loop will now dispatch 10,000 delegate invocation requests to the UI thread. It will spend several seconds executing them, not getting around to doing any real work. Like dispatch the TextBox's Paint event. Or respond to any user input. You are in fact much worse off than before.

I doubt this helps much explaining delegates. Maybe you can pick a better example, something that doesn't try to update controls.