@@ -48,8 +48,13 @@ static MultiplayerServer()
4848 public ServerSettings settings ;
4949
5050 public ServerInitData ? initData ;
51- public TaskCompletionSource < ServerInitData ? > initDataSource = new ( ) ;
52- public InitDataState initDataState = InitDataState . Waiting ;
51+ private TaskCompletionSource < ServerInitData ? > initDataSource = new ( ) ;
52+ public InitDataState InitDataState =>
53+ initData != null ? InitDataState . Complete :
54+ // started init data must've completed with null, meaning the client disconnected while waiting for the data,
55+ // so we are waiting again
56+ initDataSource . Task . IsCompleted ? InitDataState . Waiting :
57+ InitDataState . Requested ;
5358
5459 public volatile bool running ;
5560 public event Action < MultiplayerServer > ? TickEvent ;
@@ -245,16 +250,22 @@ public void RegisterChatCmd(string cmdName, ChatCmdHandler handler) =>
245250
246251 public void HandleChatCmd ( IChatSource source , string cmd ) => chatCmdManager . Handle ( source , cmd ) ;
247252
248- public Task < ServerInitData ? > InitData ( )
249- {
250- return initDataSource . Task ;
251- }
253+ public Task < ServerInitData ? > InitData ( ) => initDataSource . Task ;
252254
253- public void CompleteInitData ( ServerInitData data )
255+ /// Can only start one init data at a time. A StartInitData is considered complete once
256+ /// TaskCompletionResult.SetResult is called. Until that time no new calls to StartInitData will succeed.
257+ public TaskCompletionSource < ServerInitData ? > StartInitData ( )
254258 {
255- initData = data ;
256- initDataState = InitDataState . Complete ;
257- initDataSource . SetResult ( data ) ;
259+ if ( InitDataState != InitDataState . Waiting )
260+ throw new InvalidOperationException ( $ "Can't start init data in state { InitDataState } ") ;
261+ var currInitDataSource = initDataSource = new TaskCompletionSource < ServerInitData ? > ( ) ;
262+ currInitDataSource . Task . ContinueWith ( task =>
263+ {
264+ if ( currInitDataSource != initDataSource )
265+ ServerLog . Error ( "InitDataSource changed during StartInitData" ) ;
266+ initData = task . Result ;
267+ } , TaskContinuationOptions . ExecuteSynchronously ) ;
268+ return currInitDataSource ;
258269 }
259270 }
260271
0 commit comments