I am creating a game on Unity which will run a python script in the backend using C#, the script consists of an algorithm which takes time to load and give its output, hence I decided to use asynchronous programming. Here is my code in C#:
public static BERT instance;
public string valueSaved;
public void exec()
{
p.StartInfo = new ProcessStartInfo(pythonFile, fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
valueSaved = output;
}
public async void Activate()
{
await Task.Run(() => exec());
}
This Activate()
method is called in another class method:
private void runBERT()
{
Debug.Log("Executing BERT");
BERT.instance.Activate();
}
The code seems to be working fine, as when the runBERT()
method is called, the valueSaved
stores the output from the script after its execution, and the game stays fully resumed during this period, otherwise if I directly execute exec()
method, the game freezes until the script has fully run. However, this is the first time I have applied an async
method and all I know is that the await
keyword allows the method to leave the current thread and run in the background, but I will be implementing more of these methods, so I am not sure what I am implementing is fine for the long run, do I need to do anything else? I am just asking this to be on the safe side, so I don't run into errors or exceptions later on. The main thing I want is to store the value returned by the script in the background, which will be called later on.
Your help is much appreciated.