线程和循环 [英] Threads and Looping
问题描述
我已经在VB.NET中提出了一个简短的测试程序,看看我是否理解线程在循环中运行,而且很明显我不会。请看下面的代码并解释为什么我没有在每次循环后得到一个MsgBox。
Imports System.Threading
Public Class Form1
Dim WithEvents oSquare As SquareClass
Dim t As Thread
Public MySquare As Double
Private Sub SquareButton_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)处理SquareButton.Click
Dim x As Integer = Convert.ToInt32(TextBox1.Text)
For i As Integer = 0 to x
oSquare = New SquareClass()
oSquare.Value = Convert.ToDouble(i)
t =新线程(AddressOf oSquare.CalcSquare)
t.Start()
Next
结束子
Sub SquareEventHandler(ByVal Square As Double)_
处理oSquare.ThreadComplete
>
MySquare = Square
MsgBox(正方形是&安培;广场)
结束次级
结束班级
进口System.Threading
公共类SquareClass
公共价值双倍
公共广场双重
公共事件ThreadComplete (ByVal Square As Double)
Public Sub CalcSquare()
Thread.Sleep(1000)
SyncLock GetType(SquareClass)
Square = Value * Value
RaiseEvent ThreadComplete(Square)
结束SyncLock
结束子
结束类
I''ve come up with a short test program in VB.NET to see if I understand threads run in a loop, and it''s obvious I don''t. Please take a look at the code below and explain why I''m not getting a MsgBox back after each loop.
Imports System.Threading
Public Class Form1
Dim WithEvents oSquare As SquareClass
Dim t As Thread
Public MySquare As Double
Private Sub SquareButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SquareButton.Click
Dim x As Integer = Convert.ToInt32(TextBox1.Text)
For i As Integer = 0 To x
oSquare = New SquareClass()
oSquare.Value = Convert.ToDouble(i)
t = New Thread(AddressOf oSquare.CalcSquare)
t.Start()
Next
End Sub
Sub SquareEventHandler(ByVal Square As Double) _
Handles oSquare.ThreadComplete
MySquare = Square
MsgBox("The square is " & Square)
End Sub
End Class
Imports System.Threading
Public Class SquareClass
Public Value As Double
Public Square As Double
Public Event ThreadComplete(ByVal Square As Double)
Public Sub CalcSquare()
Thread.Sleep(1000)
SyncLock GetType(SquareClass)
Square = Value * Value
RaiseEvent ThreadComplete(Square)
End SyncLock
End Sub
End Class
推荐答案
也许我不理解vb语法,但是,你似乎没有分配你的事件处理程序?
Maybe I don''t understand vb syntax but, you don''t appear to assign your event handlers?
我以为我做了,因为我有SquareEventHandler(ByVal Square As Double)_
处理oSquare.ThreadComplete。我还应该做些什么?
I thought I did, since I have SquareEventHandler(ByVal Square As Double) _
Handles oSquare.ThreadComplete. What else should I have done?
我认为这可能会被认为是分配。
这是IS vb.net对吗?
在.Net中不是名为MessageBox.Show()的对象吗?它是我一直使用的。
我只是将你的代码转储到我的项目中并且工作正常吗?
编辑:
我刚注意到我的转换器添加了这一行:
I thought that might be considered assigning.
This IS vb.net right?
Isn''t the object called MessageBox.Show() in .Net? Its what I always use.
I just dumped your code into my project and it worked fine?
I just noticed that my converter thing added this line:
这篇关于线程和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!