Criel
Criel

Reputation: 815

How to safely access a global variable from a backgroundworker thread vb.net

I've got a backgroundworker implemented in my program and it's accessing a global variable decalred outside the thread. IT causes no errors but setting the checkillegalstring property and there are cross thread exceptions all over the place. I found out that it's because it's using the global variable I've declared previously.

I can't seem to find anywhere that I can use a global variable inside my backgroundworker thread, is this possible to do?

Upvotes: 2

Views: 3616

Answers (2)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

The simplest way is with SyncLock

Sub firstNewThread()
    SyncLock objLock
        'Access global object
    End SyncLock
End Sub
Sub secondNewThread()
    SyncLock objLock
        'Guaranteed to not be executing while block in first thread is running
    End SyncLock
End Sub

Just be aware of other pitfalls like deadlocks that may occur from this.

Upvotes: 4

user153923
user153923

Reputation:

Perhaps you can try SyncLock.

See this answer: https://stackoverflow.com/a/915877/153923

For example:

// C#
lock (someLock)
{
    list.Add(someItem);
}

// VB
SyncLock someLock
    list.Add(someItem)
End SyncLock

Upvotes: 3

Related Questions