- Home /
Question by
Sodom · Jul 09, 2018 at 07:33 PM ·
editorbackgroundplaymodemultithreading
Keep background thread alive in Editor while entering PlayMode
Fot testing purpose, I need to have tcp socket client that is connected to external server all period of Editor work. It will receive commands from external tool. So I start it by InitializeOnLoad attribute, and start it in background thread to not block the main thread. But to not finish method and to leave thread alive, I async wait endless task.
But when I start PlayMode, my thread is aborted. I've tried to use Scriptable Object with HideFlags.HideAndDontSave, but it is still died.
Example of code:
[InitializeOnLoad]
public class SocketClientLoader
{
static SocketClientLoader()
{
Debug.Log("SocketClientLoaderis called");
EditorApplication.update += StartSocketClient;
}
private static void StartSocketClient()
{
EditorApplication.update -= StartSocketClient;
SocketClient.Instance.Start();
}
}
public class SocketClient : ScriptableObject, IDisposable
{
private bool _isRun = false;
private Thread Thread;
private TcpClient client;
static SocketClient instance;
public static SocketClient Instance
{
get
{
return instance ?? (instance = CreateInstance<SocketClient>());
}
}
public async void Start()
{
if (_isRun) return;
Instance.hideFlags = HideFlags.HideAndDontSave;
Debug.Log("Thread is started");
_isRun = true;
Thread = new Thread(ProcessWork);
Thread.IsBackground = true;
Thread.Start();
await Task.Run(() =>
{
while (true)
{
Thread.Sleep(100);
if (!_isRun) return;
}
});
Debug.Log("Thread was dead");
_isRun = false;
}
public void ProcessWork()
{
//receive commands from external server
}
}
Can somebody help me with?
Additional: I use 2017 version with C# 4.6 experimental
Comment