- 生肖
- 蛇
- 星座
- 狮子座
- 性别
- 男
- 积分
- 0
- 积分
- 104
- 精华
- 1
- 阅读权限
- 100
- 注册时间
- 2013-11-3
- 最后登录
- 2014-4-4
- 帖子
- 27
- 生肖
- 蛇
- 星座
- 狮子座
- 性别
- 男
|
本帖最后由 SKY晓夜 于 2013-11-26 11:32 编辑
Imports System.Threading
Public Class Form1
#Region "Shared data"
Private mMin As Integer
Private mMax As Integer
Private mResults As New List(Of Integer)
Private value As Integer
Dim Mr As ManualResetEvent = New ManualResetEvent(True)
#End Region
#Region "Primary Thread methods"
Private Sub btnStrat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStrat.Click
ProgressBar1.Value = 0
ListBox1.Items.Clear()
mMin = 1
mMax = 10000
'启动后台线程
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
BackgroundWorker1.CancelAsync()
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
'主线程
ProgressBar1.Value = 100 + (e.ProgressPercentage)
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
'后台线程完成是显示所有素数
For Each item As String In mResults
ListBox1.Items.Add(item)
Next
End Sub
#End Region
'后台计算素数线程
#Region "Background Thread methods"
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
mResults.Clear()
For count As Integer = mMin To mMax Step 2
Dim isPtime As Boolean = True
For x As Integer = 1 To CInt(count / 2)
For y As Integer = 1 To x
If x * y = count Then
isPtime = False
Mr.WaitOne()
Exit For
End If
Next
If Not isPtime Then Exit For
Next
If isPtime Then
mResults.Add(count)
End If
Me.BackgroundWorker1.ReportProgress(CInt((count - mMax) / (mMax - mMin) * 100))
If Me.BackgroundWorker1.CancellationPending Then
Exit For
End If
Next
Mr.WaitOne()
End Sub
#End Region
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Mr.Reset()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Mr.Set()
End Sub
End Class |
|