Thread-Safe Call from async operation in BackgroundWorker

150 views Asked by At

I have a some code in BackgroundWorker which helps me to prevent freezing of interface while Bass connecting to audiostream:

Private Sub WorkerConnectToStream_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles WorkerConnectToStream.DoWork
    Bass.BASS_StreamFree(StreamNumber)
    StreamNumber = Bass.BASS_StreamCreateURL(StreamAddr, 0, BASSFlag.BASS_STREAM_STATUS, _downloadProc_, Me.Handle)
    If StreamNumber <> 0 Then
        Bass.BASS_ChannelPlay(StreamNumber, True)
    End If
End Sub

But I get: InvalidOperationException with the message, "Control control name accessed from a thread other than the thread it was created on." If I set CheckForIllegalCrossThreadCalls property to false or I launch my program from Debug folder then all is OK but it's not best solution.

if I Use:

invoke(sub()
    StreamNumber = Bass.BASS_StreamCreateURL(StreamAddr, 0, BASSFlag.BASS_STREAM_STATUS, _downloadProc_, Me.Handle)
end sub)

then this message is disappears, but interface of my form is freezes. How I can resolve this problem? Many thanks! I'm Sorry for my bad english.

1

There are 1 answers

0
T.S. On

The problem is that your DoWork runs on background thread but calls a control on main thread. Controls can't do that. You need to raise event such as ReportProgress within your Dowork, pass data and update your control there. This is what BGW is about. It lets you interact with controls without writing tons of code to manage threads.

If you use some control for something and this control is on the form, instead, try to instantiate it on BG thread and use it in-memory only. I remember, I did something like that and it worked.