How to detect within sub, the name of BacgroundProcess, sub is runned from.

Dreigo

New member
Joined
Apr 5, 2012
Messages
4
Programming Experience
1-3
Hello!

Situation:

Class Main
Dim BGW(10) as system.componentmodel.BackgrounProcess

Sub Load() handels me.load
AddHandaler BGW(0).DoWork, AddressOf BGW0_Run
AddHandaler BGW(1).DoWork, AddressOf BGW1_Run
BGW(0).RunWorkerAsync()
BGW(1).RunWorkerAsync()
RandomSub()
End Sub

Sub BGW0_Run()
RandomSub()
End Sub

Sub BGW1_Run()
RandomSub()
End Sub

Sub RandomSub()
'How to detect, is this sub powered by BackgroundWorker?
'If yes, how to tell, is sub runned by BGW(0) or BGW(1)?
'How to do this localy, so RandomSub does not accept arguments???
End Sub

End Class

Thank you for any advices!
 
At the moment i have code ~5k lines. Theres one function - Logger, that is started at the begining and the end of each sub or function. Logger registers each function/sub open & close times in ticks, and exports results. There is a conflict when the same function in the same time is runned twice (background & realtime). Only solution i see, is to pass bacground index as argument from one sub, to another, for logger to understand, that this sub is runned form bacgroundworker, but it would take too long time to mod each sub.
 
So basically you just need to be able to distinguish one thread from another. In that case you cal use Thread.CurrentThread to get access to the current Thread object and then it has an ID property of some sort so you could simply include that ID in your log message.
 
Thank you for advice, it really worked. The background has no id or name, but threads does, so i just changed them. But now i have a new problem.

Once multiple threads are started, code breaks, because all threads goes at the same time in one function, and mix up variables. Is there a way, to make each thread use separate local variables on same function?

My solution was:
'Begin logger. LoggerActive is global boolean.
Do While LoggerActive = True
System.Threading.Thread.Sleep(10)
Loop
LoggerActive = True
'...
'all code
'...
LoggerActive = False

But all threads pass this check at the same time....
 
Local variables are just that: local. They exist only in the method in which they were declared. If you call the same method twice then each instance of that method has its own set of local variables.

If you want thread-specific data then you have two options:

1. Declare a Shared field (member variable) and apply the ThreadStatic attribute to it. That field will then contain a different value on each thread.

2. Use the SetNamedDataSlot and GetNamedDataSlot methods of the Thread class.
 
You can define a class to hold the information, and use one instance of it for each thread.
 
Back
Top