IT@KMITL Forums

IT@KMITL Knowledge => ไอทีนอกกะลา => Topic started by: ^DoppLer 2 SulPhaTe^ on November 13, 2009, 02:24:56 PM

Title: ขอถามเรื่อง Thread ใน VB หน่อยครับ
Post by: ^DoppLer 2 SulPhaTe^ on November 13, 2009, 02:24:56 PM
ผมใช้ vb .net 2005

Code: [Select]
Imports System.Threading

Public Class Form1

    Dim t As Thread

    Sub test()

        Text1.AppendText("eartH")

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        t = New Thread(AddressOf Me.test)
        t.Start()
    End Sub
End Class

ทำไมเวลารันแล้ว พอคลิกปุ่ม มันจะเกิด error ที่  Text1.AppendText("eartH") หละครับ

จะอ้าง Text1 ให้ถูกต้อง ต้องอ้างยังไงครับ
Title: Re: ขอถามเรื่อง Thread ใน VB หน่อยครับ
Post by: Lord of the king on November 17, 2009, 05:56:13 PM
ถ้าน้องอยากรัน Thread แล้วให้ทำการ Set ค่าเข้า TextBox
ตอนนี้มันจะเกิด cross thread error คือ TextBox มันมี Thread ครองการใช้งานอยู่
ถ้าตามหลักของ OS ก็ต้องทำให้ TextBox มีคุณสมบัติเป็น Share ก่อน ซึ่งพี่ก็ไ่ม่รู้เหมือนกันว่า VB เค้าใช้ Keyword อะไร
แต่ถ้าอยากแค่ Set ค่าเข้า TextBox ก็ใช้โค้ดตามนี้เลย

Code: [Select]
Imports System.Threading
Public Class Form1

    Private text As String

    Private Sub Test()
        text = "Hello"
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim t As Thread
        t = New Thread(AddressOf Test)
        t.Start()
        t.Join()
        TextBox1.AppendText(text)
    End Sub
End Class

ก็ set ค่าเข้าตัวแปรก่อน แล้วค่อยนำมา set เข้าตอนรัน Thread เสร็จ
t.Join จะทำให้ Thread ทำงานเสร็จก่อนแล้วค่อยทำด้านล่างนะ