Skip to content

Commit

Permalink
Use Tasks instead of Threads
Browse files Browse the repository at this point in the history
  • Loading branch information
Rans4ckeR committed Dec 9, 2022
1 parent 0066afb commit d762991
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 101 deletions.
6 changes: 3 additions & 3 deletions ClientGUI/GameProcessLogic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using ClientCore;
using Rampastring.Tools;
using ClientCore.INIProcessing;
using System.Threading;
using System.Threading.Tasks;
using Rampastring.XNAUI;

namespace ClientGUI
Expand All @@ -26,7 +26,7 @@ public static class GameProcessLogic
/// <summary>
/// Starts the main game process.
/// </summary>
public static void StartGameProcess(WindowManager windowManager)
public static async ValueTask StartGameProcessAsync(WindowManager windowManager)
{
Logger.Log("About to launch main game executable.");

Expand All @@ -35,7 +35,7 @@ public static void StartGameProcess(WindowManager windowManager)
int waitTimes = 0;
while (PreprocessorBackgroundTask.Instance.IsRunning)
{
Thread.Sleep(1000);
await Task.Delay(1000);
waitTimes++;
if (waitTimes > 10)
{
Expand Down
23 changes: 8 additions & 15 deletions DXMainClient/DXGUI/Generic/CampaignSelector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
using System.Collections.Generic;
using DTAClient.Domain;
using System.IO;
using System.Threading.Tasks;
using ClientCore.Extensions;
using ClientGUI;
using Rampastring.XNAUI.XNAControls;
using Rampastring.XNAUI;
Expand Down Expand Up @@ -149,7 +151,7 @@ public override void Initialize()
btnLaunch.ClientRectangle = new Rectangle(12, Height - 35, UIDesignConstants.BUTTON_WIDTH_133, UIDesignConstants.BUTTON_HEIGHT);
btnLaunch.Text = "Launch".L10N("UI:Main:ButtonLaunch");
btnLaunch.AllowClick = false;
btnLaunch.LeftClick += BtnLaunch_LeftClick;
btnLaunch.LeftClick += (_, _) => BtnLaunch_LeftClickAsync().HandleTask();

var btnCancel = new XNAClientButton(WindowManager);
btnCancel.Name = "btnCancel";
Expand Down Expand Up @@ -186,7 +188,7 @@ public override void Initialize()
AddChild(dp);
dp.CenterOnParent();
cheaterWindow.CenterOnParent();
cheaterWindow.YesClicked += CheaterWindow_YesClicked;
cheaterWindow.YesClicked += (_, _) => LaunchMissionAsync(missionToLaunch).HandleTask();
cheaterWindow.Disable();
}

Expand Down Expand Up @@ -224,7 +226,7 @@ private void BtnCancel_LeftClick(object sender, EventArgs e)
Enabled = false;
}

private void BtnLaunch_LeftClick(object sender, EventArgs e)
private async ValueTask BtnLaunch_LeftClickAsync()
{
int selectedMissionId = lbCampaignList.SelectedIndex;

Expand All @@ -239,7 +241,7 @@ private void BtnLaunch_LeftClick(object sender, EventArgs e)
return;
}

LaunchMission(mission);
await LaunchMissionAsync(mission);
}

private bool AreFilesModified()
Expand All @@ -253,19 +255,10 @@ private bool AreFilesModified()
return false;
}

/// <summary>
/// Called when the user wants to proceed to the mission despite having
/// being called a cheater.
/// </summary>
private void CheaterWindow_YesClicked(object sender, EventArgs e)
{
LaunchMission(missionToLaunch);
}

/// <summary>
/// Starts a singleplayer mission.
/// </summary>
private void LaunchMission(Mission mission)
private async ValueTask LaunchMissionAsync(Mission mission)
{
bool copyMapsToSpawnmapINI = ClientConfiguration.Instance.CopyMissionsToSpawnmapINI;

Expand Down Expand Up @@ -318,7 +311,7 @@ private void LaunchMission(Mission mission)
discordHandler.UpdatePresence(mission.GUIName, difficultyName, mission.IconPath, true);
GameProcessLogic.GameProcessExited += GameProcessExited_Callback;

GameProcessLogic.StartGameProcess(WindowManager);
await GameProcessLogic.StartGameProcessAsync(WindowManager);
}

private int GetComputerDifficulty() =>
Expand Down
10 changes: 6 additions & 4 deletions DXMainClient/DXGUI/Generic/GameLoadingWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ClientCore.Extensions;

namespace DTAClient.DXGUI.Generic
{
Expand Down Expand Up @@ -55,7 +57,7 @@ public override void Initialize()
btnLaunch.ClientRectangle = new Rectangle(125, 345, 110, 23);
btnLaunch.Text = "Load".L10N("UI:Main:ButtonLoad");
btnLaunch.AllowClick = false;
btnLaunch.LeftClick += BtnLaunch_LeftClick;
btnLaunch.LeftClick += (_, _) => BtnLaunch_LeftClickAsync().HandleTask();

btnDelete = new XNAClientButton(WindowManager);
btnDelete.Name = nameof(btnDelete);
Expand Down Expand Up @@ -99,7 +101,7 @@ private void BtnCancel_LeftClick(object sender, EventArgs e)
Enabled = false;
}

private void BtnLaunch_LeftClick(object sender, EventArgs e)
private async ValueTask BtnLaunch_LeftClickAsync()
{
SavedGame sg = savedGames[lbSaveGameList.SelectedIndex];
Logger.Log("Loading saved game " + sg.FileName);
Expand Down Expand Up @@ -137,7 +139,7 @@ private void BtnLaunch_LeftClick(object sender, EventArgs e)
Enabled = false;
GameProcessLogic.GameProcessExited += GameProcessExited_Callback;

GameProcessLogic.StartGameProcess(WindowManager);
await GameProcessLogic.StartGameProcessAsync(WindowManager);
}

private void BtnDelete_LeftClick(object sender, EventArgs e)
Expand Down Expand Up @@ -219,4 +221,4 @@ private void ParseSaveGame(string fileName)
savedGames.Add(sg);
}
}
}
}
25 changes: 10 additions & 15 deletions DXMainClient/DXGUI/Generic/MainMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public override void Initialize()
btnExit.IdleTexture = AssetLoader.LoadTexture("MainMenu/exitgame.png");
btnExit.HoverTexture = AssetLoader.LoadTexture("MainMenu/exitgame_c.png");
btnExit.HoverSoundEffect = new EnhancedSoundEffect("MainMenu/button.wav");
btnExit.LeftClick += BtnExit_LeftClick;
btnExit.LeftClick += (_, _) => BtnExit_LeftClickAsync().HandleTask();

XNALabel lblCnCNetStatus = new XNALabel(WindowManager);
lblCnCNetStatus.Name = nameof(lblCnCNetStatus);
Expand Down Expand Up @@ -312,10 +312,8 @@ public override void Initialize()

GameProcessLogic.GameProcessStarted += SharedUILogic_GameProcessStarted;
GameProcessLogic.GameProcessStarting += SharedUILogic_GameProcessStarting;

UserINISettings.Instance.SettingsSaved += SettingsSaved;

Updater.Restart += Updater_Restart;
Updater.Restart += (_, _) => WindowManager.AddCallback(() => ExitClientAsync().HandleTask());

SetButtonHotkeys(true);
}
Expand Down Expand Up @@ -379,9 +377,6 @@ private void SharedUILogic_GameProcessStarting()
}
}

private void Updater_Restart(object sender, EventArgs e) =>
WindowManager.AddCallback(ExitClient);

/// <summary>
/// Applies configuration changes (music playback and volume)
/// when settings are saved.
Expand Down Expand Up @@ -868,12 +863,12 @@ private void BtnCredits_LeftClick(object sender, EventArgs e)
private void BtnExtras_LeftClick(object sender, EventArgs e) =>
innerPanel.Show(innerPanel.ExtrasWindow);

private void BtnExit_LeftClick(object sender, EventArgs e)
private ValueTask BtnExit_LeftClickAsync()
{
#if WINFORMS
WindowManager.HideWindow();
#endif
FadeMusicExit();
return FadeMusicExitAsync();
}

private void SharedUILogic_GameProcessExited() =>
Expand Down Expand Up @@ -969,11 +964,11 @@ private void FadeMusic(GameTime gameTime)
/// <summary>
/// Exits the client. Quickly fades the music if it's playing.
/// </summary>
private void FadeMusicExit()
private async ValueTask FadeMusicExitAsync()
{
if (!isMediaPlayerAvailable || themeSong == null)
{
ExitClient();
await ExitClientAsync();
return;
}

Expand All @@ -982,21 +977,21 @@ private void FadeMusicExit()
if (MediaPlayer.Volume > step)
{
MediaPlayer.Volume -= step;
AddCallback(FadeMusicExit);
AddCallback(() => FadeMusicExitAsync().HandleTask());
}
else
{
MediaPlayer.Stop();
ExitClient();
await ExitClientAsync();
}
}

private void ExitClient()
private async ValueTask ExitClientAsync()
{
Logger.Log("Exiting.");
WindowManager.CloseGame();
#if !XNA
Thread.Sleep(1000);
await Task.Delay(1000);
Environment.Exit(0);
#endif
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public CnCNetGameLoadingLobby(
new IntCommandHandler(CnCNetCommands.TUNNEL_PING, HandleTunnelPing),
new StringCommandHandler(CnCNetCommands.OPTIONS, (sender, data) => HandleOptionsMessageAsync(sender, data).HandleTask()),
new NoParamCommandHandler(CnCNetCommands.INVALID_SAVED_GAME_INDEX, HandleInvalidSaveIndexCommand),
new StringCommandHandler(CnCNetCommands.START_GAME, HandleStartGameCommand),
new StringCommandHandler(CnCNetCommands.START_GAME, (sender, data) => HandleStartGameCommandAsync(sender, data).HandleTask()),
new IntCommandHandler(CnCNetCommands.PLAYER_READY, (sender, readyStatus) => HandlePlayerReadyRequestAsync(sender, readyStatus).HandleTask()),
new StringCommandHandler(CnCNetCommands.CHANGE_TUNNEL_SERVER, HandleTunnelServerChangeMessage)
};
Expand Down Expand Up @@ -489,7 +489,7 @@ private void HandleInvalidSaveIndexCommand(string sender)
CopyPlayerDataToUI();
}

private void HandleStartGameCommand(string sender, string data)
private async ValueTask HandleStartGameCommandAsync(string sender, string data)
{
if (sender != hostName)
return;
Expand Down Expand Up @@ -523,7 +523,7 @@ private void HandleStartGameCommand(string sender, string data)
pInfo.Port = port;
}

LoadGame();
await LoadGameAsync();
}

private async ValueTask HandlePlayerReadyRequestAsync(string sender, int readyStatus)
Expand Down Expand Up @@ -606,7 +606,7 @@ protected override async ValueTask HostStartGameAsync()

started = true;

LoadGame();
await LoadGameAsync();
}

protected override void WriteSpawnIniAdditions(IniFile spawnIni)
Expand Down
7 changes: 3 additions & 4 deletions DXMainClient/DXGUI/Multiplayer/CnCNet/CnCNetLobby.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1111,8 +1111,8 @@ private void ConnectionManager_Disconnected(object sender, EventArgs e)
ddCurrentChannel.SelectedIndex = gameIndex;
}

if (gameCheckCancellation != null)
gameCheckCancellation.Cancel();
gameCheckCancellation?.Cancel();
gameCheckCancellation?.Dispose();
}

private async ValueTask ConnectionManager_WelcomeMessageReceivedAsync()
Expand Down Expand Up @@ -1147,8 +1147,7 @@ private async ValueTask ConnectionManager_WelcomeMessageReceivedAsync()
}

gameCheckCancellation = new CancellationTokenSource();
CnCNetGameCheck gameCheck = new CnCNetGameCheck();
gameCheck.InitializeService(gameCheckCancellation);
CnCNetGameCheck.RunServiceAsync(gameCheckCancellation.Token).HandleTask();
}

private void ConnectionManager_PrivateCTCPReceived(object sender, PrivateCTCPEventArgs e)
Expand Down
4 changes: 2 additions & 2 deletions DXMainClient/DXGUI/Multiplayer/GameLoadingLobbyBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ protected virtual ValueTask NotAllPresentNotificationAsync()

protected abstract ValueTask HostStartGameAsync();

protected void LoadGame()
protected async ValueTask LoadGameAsync()
{
FileInfo spawnFileInfo = SafePath.GetFile(ProgramConstants.GamePath, ProgramConstants.SPAWNER_SETTINGS);

Expand Down Expand Up @@ -340,7 +340,7 @@ protected void LoadGame()
gameLoadTime = DateTime.Now;

GameProcessLogic.GameProcessExited += SharedUILogic_GameProcessExited;
GameProcessLogic.StartGameProcess(WindowManager);
await GameProcessLogic.StartGameProcessAsync(WindowManager);

fsw.EnableRaisingEvents = true;
UpdateDiscordPresence(true);
Expand Down
6 changes: 2 additions & 4 deletions DXMainClient/DXGUI/Multiplayer/GameLobby/GameLobbyBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1640,18 +1640,16 @@ private void ManipulateStartingLocations(IniFile mapIni, PlayerHouseInfo[] house
/// Writes spawn.ini, writes the map file, initializes statistics and
/// starts the game process.
/// </summary>
protected virtual ValueTask StartGameAsync()
protected virtual async ValueTask StartGameAsync()
{
PlayerHouseInfo[] houseInfos = WriteSpawnIni();
InitializeMatchStatistics(houseInfos);
WriteMap(houseInfos);

GameProcessLogic.GameProcessExited += GameProcessExited_Callback;

GameProcessLogic.StartGameProcess(WindowManager);
await GameProcessLogic.StartGameProcessAsync(WindowManager);
UpdateDiscordPresence(true);

return ValueTask.CompletedTask;
}

private void GameProcessExited_Callback() => AddCallback(() => GameProcessExitedAsync().HandleTask());
Expand Down
6 changes: 3 additions & 3 deletions DXMainClient/DXGUI/Multiplayer/LANGameLoadingLobby.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public LANGameLoadingLobby(
{
new ClientStringCommandHandler(LANCommands.CHAT_GAME_LOADING_COMMAND, Client_HandleChatMessage),
new ClientStringCommandHandler(LANCommands.OPTIONS, Client_HandleOptionsMessage),
new ClientNoParamCommandHandler(LANCommands.GAME_START, Client_HandleStartCommand)
new ClientNoParamCommandHandler(LANCommands.GAME_START, () => Client_HandleStartCommandAsync().HandleTask())
};

WindowManager.GameClosing += (_, _) => WindowManager_GameClosingAsync().HandleTask();
Expand Down Expand Up @@ -556,11 +556,11 @@ private void Client_HandleOptionsMessage(string data)
CopyPlayerDataToUI();
}

private void Client_HandleStartCommand()
private ValueTask Client_HandleStartCommandAsync()
{
started = true;

LoadGame();
return LoadGameAsync();
}

#endregion
Expand Down
Loading

0 comments on commit d762991

Please sign in to comment.