how to keep matlab after close C# winform

1 view (last 30 days)
Vincent Hoang
Vincent Hoang on 23 May 2023
Answered: Hitesh on 29 Jan 2025
We use C# to call some functions in Matlab
After we close our program, the matlab is also closed
MLApp.MLApp matlab;
Console.Write("\nPlease wait to load MatLab ...");
matlab = new MLApp.MLApp();
matlab.Execute(@"cd C:\Data");
Console.WriteLine("Done !");
Next our program is running, it will take a long time to load Matlab again
Is there any method to load Matlab and any program could use and run faster ?
Thanks,

Answers (1)

Hitesh
Hitesh on 29 Jan 2025
HI Vincent,
You need to create persistent MATLAB session running in the background which would improve the performance of your application when using MATLAB from C#. This will help you in avoiding restarting of MATLAB every time you run your program.
You need to create a singleton pattern for MATLAB Instance that will ensure that only one instance of MATLAB is created and reused across your application. This will prevent multiple startups of MATLAB, which can be time-consuming. Use "MatlabSingleton.GetInstance()" command whenever you need to use MATLAB in your application.
public class MatlabSingleton
{
private static MLApp.MLApp _matlabInstance;
private static readonly object _lock = new object();
private MatlabSingleton() { }
public static MLApp.MLApp GetInstance()
{
if (_matlabInstance == null)
{
lock (_lock)
{
if (_matlabInstance == null)
{
_matlabInstance = new MLApp.MLApp();
_matlabInstance.Execute(@"cd C:\Data");
}
}
}
return _matlabInstance;
}
}

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!