Link to home
Start Free TrialLog in
Avatar of PNRT
PNRT

asked on

VB.Net Explanation on Multithreading needed

Hi Experts.  

In VB.Net, I have a process in a single sub that carries out certain checks and then sends messages.  In carrying out the checks it calls a socket.Receive function to test the availability of a server.

This works well but takes about 3 to 5 seconds to run and could run up to 2000 times.   Due to the time, I changed things so that the sub is called on different threads, with this code

 Dim NewThread As New System.Threading.Thread(AddressOf StartTheProcess)
 NewThread.Start()

This works well if the sub is not called to quickly, once every second seems OK.  But faster than this I get errors relating to the socket function.  

My question is - if the sub is running multiple times, will there be multiple calls to the same socket function at the same time or is it separated in some way?

In general, in multithreading, if there is a function called from different threads, do they interact with the same function.

If this is the case, what is the way round it?

Thanks for any help.
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

Well, if you call a function, you call a function. So yes if you call it from different threads, it will be called many times.

There are many possible reasons that can cause things to go bad in multithreading. A frequent one is the following.

Multithread involves the system switching continually between the different threads. It is quite possible that one call starts the function, then the system switch to another thread before the function as terminated its job. If the function locked a resource and the switch occured before that resource was freed, the call from the second thread might bomb because the resource is locked.

Not all functions are thread-safe. You need to check the documentation. You might also see if there is not an asynchrone equivalent of that function. Asynchrone functions usually automatically works on a their own thread and have been designed to handle the type of problem I described. Typically, an Async function will have the same name as the original function with Async as a suffix (GetData and GetDataAsync). But there might also be an alternative that has a complete different name. If you have some, check the documentation for the class that contains your function.
Avatar of PNRT
PNRT

ASKER

Many Thanks James
What if I was to have the new thread open a further thread on which the same functionality as the function could be handled.  I would think that this would be kept separate for each thread?
ASKER CERTIFIED SOLUTION
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of PNRT

ASKER

Thanks James