function OK = wait( workunit, state, timeout )
% wait - general implementation of "wait"

% Copyright 2011-2019 The MathWorks, Inc.

try
    workunit.hWarnIfNotSubmitted();
    startTime = tic;
    waitInterval = iGetWaitInterval();
    while true
        OK = (workunit.hGetStateEnum() >= state);
        if OK || toc(startTime) > timeout
            break
        end
        pause(waitInterval);
    end
catch err
    % The object might become invalid during the waitForEvent. Only
    % bother with errors if the object is still valid
    if isvalid( workunit )
        rethrow( err );
    end
end
end

function waitInterval = iGetWaitInterval()
[~, undocConfig] = pctconfig;
waitInterval = undocConfig.cjspollinterval;
end