RobotStudio event

Application problem with Mastership release

Options
I'm testing one of the functions in c# application. Something happened and my Robot Studio virtual station is stuck with - Remote Write Access - from one of my testing. Not sure what exactly happened but I glad it did. Now when I trying to run my application is throwing me an exception - Requested resource is held by someone else. Now I need to come up with the solution if this happens in production. How can I check if is Mastership is held by someone else and if yes then dispose or check if it's my mastership and if it's mine then continue?
This is an example of my code where is throwing an exception:


try
            {
                if (controller.OperatingMode == ControllerOperatingMode.Auto)
                {
                    tasks = controller.Rapid.GetTasks();

                    using (Mastership m = Mastership.Request(controller.Rapid))   // on this line is throwing  an exception
                    {
                        if (m.IsMaster != true)
                        {
                            tasks[0].LoadModuleFromFile(filePath, RapidLoadMode.Replace);
                            //controller.IOSystem.GetSignal($"{startSignal}");
                            // set digital signal
                            //Signal sig = controller.IOSystem.GetSignal(startSignal);
                            //digitalSig = (DigitalSignal)sig;
                            //Perform operation 
                            tasks[0].Start();
                        }
                    }
                }

Will appreciate any help.
Thank you,
Tagged: