Pass NET-Object to parallel function (parfeval)

3 views (last 30 days)
I am trying to pass a NET-Object to a function running on a parallel pool in Matlab.
While I thought "parallel.pool.Constant" is the way to do it - as it works fine for other objects (like database connection) - it doesn't work in this case.
As I don't receive an error message, I can't find out why it won't work as it should.
Also the display function doesn't show anything.
%% Import Ads.dll
AdsAssembly = NET.addAssembly('D:\TwinCat3\AdsApi\.NET\v4.0.30319\TwinCAT.Ads.dll');
import TwinCAT.Ads.*;
%Create TcAdsClient instance
tcClient = TcAdsClient;
tc = parallel.pool.Constant(tcClient); %Create pool constant to pass object
pool = gcp();
function pfcn(tc)
tcClient = tc.Value;
tcClient.Connect(851); %Connect to ADS port 851 on the local machine
An example where it works fine (OPC UA Client):
pool = gcp();
Q = parallel.pool.DataQueue;
serverList = opcuaserverinfo('');
hsInfo = findDescription(serverList, 'K6');
uaClient = opcua(hsInfo);
opc_const = parallel.pool.Constant(uaClient);
parfeval(pool, @pfcn, 0, Q, opc_const);
listener = afterEach(Q, @disp);
function pfcn(Q, opc_const)
par_uaClient = opc_const.Value;
conn_state = isConnected(par_uaClient);
send(Q, par_uaClient)

Answers (1)

Edric Ellis
Edric Ellis on 14 Apr 2020
I do think parallel.pool.Constant is probably part of the answer here, but you need to make two changes:
  1. Make sure you perform the initialisation steps on the workers
  2. Use the form of parallel.pool.Constant constructor that takes a function handle so that the object is built directly on the worker. (The code you have builds the object on the client and then attempts to send it to the worker)
Something like this:
% Call NET.addAssembly on all workers
parfevalOnAll(@() NET.addAssembly('D:\TwinCat3\AdsApi\.NET\v4.0.30319\TwinCAT.Ads.dll'), 0);
% Build parallel.pool.Constant using function handle
tcClient = parallel.pool.Constant(@TwinCAT.Ads.TcAdsClient);
If there's a specific "cleanup" function needed for your object, you can specify this as the second argument to the parallel.pool.Constant constructor.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!