1
0
mirror of https://github.com/ppy/osu.git synced 2025-01-06 12:39:35 +08:00

Apply ConfigureAwait changes to game side

This commit is contained in:
Dean Herbert 2021-03-08 12:57:16 +09:00
parent 85bad1ab89
commit b1cd01ceb8
25 changed files with 65 additions and 66 deletions

View File

@ -30,7 +30,7 @@
<Rule Id="CA1819" Action="None" />
<Rule Id="CA1822" Action="None" />
<Rule Id="CA1823" Action="None" />
<Rule Id="CA2007" Action="None" />
<Rule Id="CA2007" Action="Warning" />
<Rule Id="CA2214" Action="None" />
<Rule Id="CA2227" Action="None" />
</Rules>

View File

@ -42,7 +42,7 @@ namespace osu.Desktop.Updater
Splat.Locator.CurrentMutable.Register(() => new SquirrelLogger(), typeof(Splat.ILogger));
}
protected override async Task<bool> PerformUpdateCheck() => await checkForUpdateAsync();
protected override async Task<bool> PerformUpdateCheck() => await checkForUpdateAsync().ConfigureAwait(false);
private async Task<bool> checkForUpdateAsync(bool useDeltaPatching = true, UpdateProgressNotification notification = null)
{
@ -51,9 +51,9 @@ namespace osu.Desktop.Updater
try
{
updateManager ??= await UpdateManager.GitHubUpdateManager(@"https://github.com/ppy/osu", @"osulazer", null, null, true);
updateManager ??= await UpdateManager.GitHubUpdateManager(@"https://github.com/ppy/osu", @"osulazer", null, null, true).ConfigureAwait(false);
var info = await updateManager.CheckForUpdate(!useDeltaPatching);
var info = await updateManager.CheckForUpdate(!useDeltaPatching).ConfigureAwait(false);
if (info.ReleasesToApply.Count == 0)
{
@ -79,12 +79,12 @@ namespace osu.Desktop.Updater
try
{
await updateManager.DownloadReleases(info.ReleasesToApply, p => notification.Progress = p / 100f);
await updateManager.DownloadReleases(info.ReleasesToApply, p => notification.Progress = p / 100f).ConfigureAwait(false);
notification.Progress = 0;
notification.Text = @"Installing update...";
await updateManager.ApplyReleases(info, p => notification.Progress = p / 100f);
await updateManager.ApplyReleases(info, p => notification.Progress = p / 100f).ConfigureAwait(false);
notification.State = ProgressNotificationState.Completed;
updatePending = true;
@ -97,7 +97,7 @@ namespace osu.Desktop.Updater
// could fail if deltas are unavailable for full update path (https://github.com/Squirrel/Squirrel.Windows/issues/959)
// try again without deltas.
await checkForUpdateAsync(false, notification);
await checkForUpdateAsync(false, notification).ConfigureAwait(false);
scheduleRecheck = false;
}
else
@ -116,7 +116,7 @@ namespace osu.Desktop.Updater
if (scheduleRecheck)
{
// check again in 30 minutes.
Scheduler.AddDelayed(async () => await checkForUpdateAsync(), 60000 * 30);
Scheduler.AddDelayed(async () => await checkForUpdateAsync().ConfigureAwait(false), 60000 * 30);
}
}

View File

@ -156,7 +156,7 @@ namespace osu.Game.Beatmaps
bool hadOnlineBeatmapIDs = beatmapSet.Beatmaps.Any(b => b.OnlineBeatmapID > 0);
if (onlineLookupQueue != null)
await onlineLookupQueue.UpdateAsync(beatmapSet, cancellationToken);
await onlineLookupQueue.UpdateAsync(beatmapSet, cancellationToken).ConfigureAwait(false);
// ensure at least one beatmap was able to retrieve or keep an online ID, else drop the set ID.
if (hadOnlineBeatmapIDs && !beatmapSet.Beatmaps.Any(b => b.OnlineBeatmapID > 0))

View File

@ -124,7 +124,7 @@ namespace osu.Game.Collections
return Task.Run(async () =>
{
using (var stream = stable.GetStream(database_name))
await Import(stream);
await Import(stream).ConfigureAwait(false);
});
}
@ -139,7 +139,7 @@ namespace osu.Game.Collections
PostNotification?.Invoke(notification);
var collections = readCollections(stream, notification);
await importCollections(collections);
await importCollections(collections).ConfigureAwait(false);
notification.CompletionText = $"Imported {collections.Count} collections";
notification.State = ProgressNotificationState.Completed;

View File

@ -22,7 +22,6 @@ using osu.Game.IO.Archives;
using osu.Game.IPC;
using osu.Game.Overlays.Notifications;
using SharpCompress.Archives.Zip;
using FileInfo = osu.Game.IO.FileInfo;
namespace osu.Game.Database
{
@ -163,7 +162,7 @@ namespace osu.Game.Database
try
{
var model = await Import(task, isLowPriorityImport, notification.CancellationToken);
var model = await Import(task, isLowPriorityImport, notification.CancellationToken).ConfigureAwait(false);
lock (imported)
{
@ -183,7 +182,7 @@ namespace osu.Game.Database
{
Logger.Error(e, $@"Could not import ({task})", LoggingTarget.Database);
}
}));
})).ConfigureAwait(false);
if (imported.Count == 0)
{
@ -226,7 +225,7 @@ namespace osu.Game.Database
TModel import;
using (ArchiveReader reader = task.GetReader())
import = await Import(reader, lowPriority, cancellationToken);
import = await Import(reader, lowPriority, cancellationToken).ConfigureAwait(false);
// We may or may not want to delete the file depending on where it is stored.
// e.g. reconstructing/repairing database with items from default storage.
@ -358,7 +357,7 @@ namespace osu.Game.Database
item.Files = archive != null ? createFileInfos(archive, Files) : new List<TFileModel>();
item.Hash = ComputeHash(item, archive);
await Populate(item, archive, cancellationToken);
await Populate(item, archive, cancellationToken).ConfigureAwait(false);
using (var write = ContextFactory.GetForWrite()) // used to share a context for full import. keep in mind this will block all writes.
{
@ -410,7 +409,7 @@ namespace osu.Game.Database
flushEvents(true);
return item;
}, cancellationToken, TaskCreationOptions.HideScheduler, lowPriority ? import_scheduler_low_priority : import_scheduler).Unwrap();
}, cancellationToken, TaskCreationOptions.HideScheduler, lowPriority ? import_scheduler_low_priority : import_scheduler).Unwrap().ConfigureAwait(false);
/// <summary>
/// Exports an item to a legacy (.zip based) package.
@ -621,7 +620,7 @@ namespace osu.Game.Database
}
/// <summary>
/// Create all required <see cref="FileInfo"/>s for the provided archive, adding them to the global file store.
/// Create all required <see cref="IO.FileInfo"/>s for the provided archive, adding them to the global file store.
/// </summary>
private List<TFileModel> createFileInfos(ArchiveReader reader, FileStore files)
{
@ -699,7 +698,7 @@ namespace osu.Game.Database
return Task.CompletedTask;
}
return Task.Run(async () => await Import(GetStableImportPaths(storage).ToArray()));
return Task.Run(async () => await Import(GetStableImportPaths(storage).ToArray()).ConfigureAwait(false));
}
/// <summary>

View File

@ -82,7 +82,7 @@ namespace osu.Game.Database
Task.Factory.StartNew(async () =>
{
// This gets scheduled back to the update thread, but we want the import to run in the background.
var imported = await Import(notification, new ImportTask(filename));
var imported = await Import(notification, new ImportTask(filename)).ConfigureAwait(false);
// for now a failed import will be marked as a failed download for simplicity.
if (!imported.Any())

View File

@ -29,7 +29,7 @@ namespace osu.Game.Database
if (CheckExists(lookup, out TValue performance))
return performance;
var computed = await ComputeValueAsync(lookup, token);
var computed = await ComputeValueAsync(lookup, token).ConfigureAwait(false);
if (computed != null || CacheNullValues)
cache[lookup] = computed;

View File

@ -28,7 +28,7 @@ namespace osu.Game.Database
public Task<User> GetUserAsync(int userId, CancellationToken token = default) => GetAsync(userId, token);
protected override async Task<User> ComputeValueAsync(int lookup, CancellationToken token = default)
=> await queryUser(lookup);
=> await queryUser(lookup).ConfigureAwait(false);
private readonly Queue<(int id, TaskCompletionSource<User>)> pendingUserTasks = new Queue<(int, TaskCompletionSource<User>)>();
private Task pendingRequestTask;

View File

@ -103,7 +103,7 @@ namespace osu.Game.Graphics
}
}
using (var image = await host.TakeScreenshotAsync())
using (var image = await host.TakeScreenshotAsync().ConfigureAwait(false))
{
if (Interlocked.Decrement(ref screenShotTasks) == 0 && cursorVisibility.Value == false)
cursorVisibility.Value = true;
@ -116,13 +116,13 @@ namespace osu.Game.Graphics
switch (screenshotFormat.Value)
{
case ScreenshotFormat.Png:
await image.SaveAsPngAsync(stream);
await image.SaveAsPngAsync(stream).ConfigureAwait(false);
break;
case ScreenshotFormat.Jpg:
const int jpeg_quality = 92;
await image.SaveAsJpegAsync(stream, new JpegEncoder { Quality = jpeg_quality });
await image.SaveAsJpegAsync(stream, new JpegEncoder { Quality = jpeg_quality }).ConfigureAwait(false);
break;
default:

View File

@ -41,7 +41,7 @@ namespace osu.Game.IO.Archives
return null;
byte[] buffer = new byte[input.Length];
await input.ReadAsync(buffer);
await input.ReadAsync(buffer).ConfigureAwait(false);
return buffer;
}
}

View File

@ -33,12 +33,12 @@ namespace osu.Game.IPC
if (importer == null)
{
// we want to contact a remote osu! to handle the import.
await SendMessageAsync(new ArchiveImportMessage { Path = path });
await SendMessageAsync(new ArchiveImportMessage { Path = path }).ConfigureAwait(false);
return;
}
if (importer.HandledExtensions.Contains(Path.GetExtension(path)?.ToLowerInvariant()))
await importer.Import(path);
await importer.Import(path).ConfigureAwait(false);
}
}

View File

@ -79,7 +79,7 @@ namespace osu.Game.Online
{
cancelExistingConnect();
if (!await connectionLock.WaitAsync(10000))
if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false))
throw new TimeoutException("Could not obtain a lock to connect. A previous attempt is likely stuck.");
try
@ -88,7 +88,7 @@ namespace osu.Game.Online
{
// ensure any previous connection was disposed.
// this will also create a new cancellation token source.
await disconnect(false);
await disconnect(false).ConfigureAwait(false);
// this token will be valid for the scope of this connection.
// if cancelled, we can be sure that a disconnect or reconnect is handled elsewhere.
@ -103,7 +103,7 @@ namespace osu.Game.Online
// importantly, rebuild the connection each attempt to get an updated access token.
CurrentConnection = buildConnection(cancellationToken);
await CurrentConnection.StartAsync(cancellationToken);
await CurrentConnection.StartAsync(cancellationToken).ConfigureAwait(false);
Logger.Log($"{clientName} connected!", LoggingTarget.Network);
isConnected.Value = true;
@ -119,7 +119,7 @@ namespace osu.Game.Online
Logger.Log($"{clientName} connection error: {e}", LoggingTarget.Network);
// retry on any failure.
await Task.Delay(5000, cancellationToken);
await Task.Delay(5000, cancellationToken).ConfigureAwait(false);
}
}
}
@ -174,14 +174,14 @@ namespace osu.Game.Online
if (takeLock)
{
if (!await connectionLock.WaitAsync(10000))
if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false))
throw new TimeoutException("Could not obtain a lock to disconnect. A previous attempt is likely stuck.");
}
try
{
if (CurrentConnection != null)
await CurrentConnection.DisposeAsync();
await CurrentConnection.DisposeAsync().ConfigureAwait(false);
}
finally
{

View File

@ -131,12 +131,12 @@ namespace osu.Game.Online.Multiplayer
Debug.Assert(room.RoomID.Value != null);
// Join the server-side room.
var joinedRoom = await JoinRoom(room.RoomID.Value.Value);
var joinedRoom = await JoinRoom(room.RoomID.Value.Value).ConfigureAwait(false);
Debug.Assert(joinedRoom != null);
// Populate users.
Debug.Assert(joinedRoom.Users != null);
await Task.WhenAll(joinedRoom.Users.Select(PopulateUser));
await Task.WhenAll(joinedRoom.Users.Select(PopulateUser)).ConfigureAwait(false);
// Update the stored room (must be done on update thread for thread-safety).
await scheduleAsync(() =>
@ -144,11 +144,11 @@ namespace osu.Game.Online.Multiplayer
Room = joinedRoom;
apiRoom = room;
defaultPlaylistItemId = apiRoom.Playlist.FirstOrDefault()?.ID ?? 0;
}, cancellationSource.Token);
}, cancellationSource.Token).ConfigureAwait(false);
// Update room settings.
await updateLocalRoomSettings(joinedRoom.Settings, cancellationSource.Token);
}, cancellationSource.Token);
await updateLocalRoomSettings(joinedRoom.Settings, cancellationSource.Token).ConfigureAwait(false);
}, cancellationSource.Token).ConfigureAwait(false);
}
/// <summary>
@ -178,8 +178,8 @@ namespace osu.Game.Online.Multiplayer
return joinOrLeaveTaskChain.Add(async () =>
{
await scheduledReset;
await LeaveRoomInternal();
await scheduledReset.ConfigureAwait(false);
await LeaveRoomInternal().ConfigureAwait(false);
});
}
@ -237,11 +237,11 @@ namespace osu.Game.Online.Multiplayer
switch (localUser.State)
{
case MultiplayerUserState.Idle:
await ChangeState(MultiplayerUserState.Ready);
await ChangeState(MultiplayerUserState.Ready).ConfigureAwait(false);
return;
case MultiplayerUserState.Ready:
await ChangeState(MultiplayerUserState.Idle);
await ChangeState(MultiplayerUserState.Idle).ConfigureAwait(false);
return;
default:
@ -307,7 +307,7 @@ namespace osu.Game.Online.Multiplayer
if (Room == null)
return;
await PopulateUser(user);
await PopulateUser(user).ConfigureAwait(false);
Scheduler.Add(() =>
{
@ -486,7 +486,7 @@ namespace osu.Game.Online.Multiplayer
/// Populates the <see cref="User"/> for a given <see cref="MultiplayerRoomUser"/>.
/// </summary>
/// <param name="multiplayerUser">The <see cref="MultiplayerRoomUser"/> to populate.</param>
protected async Task PopulateUser(MultiplayerRoomUser multiplayerUser) => multiplayerUser.User ??= await userLookupCache.GetUserAsync(multiplayerUser.UserID);
protected async Task PopulateUser(MultiplayerRoomUser multiplayerUser) => multiplayerUser.User ??= await userLookupCache.GetUserAsync(multiplayerUser.UserID).ConfigureAwait(false);
/// <summary>
/// Updates the local room settings with the given <see cref="MultiplayerRoomSettings"/>.

View File

@ -440,7 +440,7 @@ namespace osu.Game
public override Task Import(params ImportTask[] imports)
{
// encapsulate task as we don't want to begin the import process until in a ready state.
var importTask = new Task(async () => await base.Import(imports));
var importTask = new Task(async () => await base.Import(imports).ConfigureAwait(false));
waitForReady(() => this, _ => importTask.Start());
@ -831,7 +831,7 @@ namespace osu.Game
asyncLoadStream = Task.Run(async () =>
{
if (previousLoadStream != null)
await previousLoadStream;
await previousLoadStream.ConfigureAwait(false);
try
{
@ -845,7 +845,7 @@ namespace osu.Game
// The delegate won't complete if OsuGame has been disposed in the meantime
while (!IsDisposed && !del.Completed)
await Task.Delay(10);
await Task.Delay(10).ConfigureAwait(false);
// Either we're disposed or the load process has started successfully
if (IsDisposed)
@ -853,7 +853,7 @@ namespace osu.Game
Debug.Assert(task != null);
await task;
await task.ConfigureAwait(false);
Logger.Log($"Loaded {component}!", level: LogLevel.Debug);
}

View File

@ -434,7 +434,7 @@ namespace osu.Game
foreach (var importer in fileImporters)
{
if (importer.HandledExtensions.Contains(extension))
await importer.Import(paths);
await importer.Import(paths).ConfigureAwait(false);
}
}
@ -445,7 +445,7 @@ namespace osu.Game
{
var importer = fileImporters.FirstOrDefault(i => i.HandledExtensions.Contains(taskGroup.Key));
return importer?.Import(taskGroup.ToArray()) ?? Task.CompletedTask;
}));
})).ConfigureAwait(false);
}
public IEnumerable<string> HandledExtensions => fileImporters.SelectMany(i => i.HandledExtensions);

View File

@ -160,9 +160,9 @@ namespace osu.Game.Overlays
tcs.SetException(e);
};
await API.PerformAsync(req);
await API.PerformAsync(req).ConfigureAwait(false);
await tcs.Task;
return tcs.Task;
});
}

View File

@ -34,7 +34,7 @@ namespace osu.Game.Scoring
{
var score = lookup.ScoreInfo;
var attributes = await difficultyCache.GetDifficultyAsync(score.Beatmap, score.Ruleset, score.Mods, token);
var attributes = await difficultyCache.GetDifficultyAsync(score.Beatmap, score.Ruleset, score.Mods, token).ConfigureAwait(false);
// Performance calculation requires the beatmap and ruleset to be locally available. If not, return a default value.
if (attributes.Attributes == null)

View File

@ -154,7 +154,7 @@ namespace osu.Game.Screens.Import
Task.Factory.StartNew(async () =>
{
await game.Import(path);
await game.Import(path).ConfigureAwait(false);
// some files will be deleted after successful import, so we want to refresh the view.
Schedule(() =>

View File

@ -137,13 +137,13 @@ namespace osu.Game.Screens.OnlinePlay.Multiplayer
protected override async Task SubmitScore(Score score)
{
await base.SubmitScore(score);
await base.SubmitScore(score).ConfigureAwait(false);
await client.ChangeState(MultiplayerUserState.FinishedPlay);
await client.ChangeState(MultiplayerUserState.FinishedPlay).ConfigureAwait(false);
// Await up to 60 seconds for results to become available (6 api request timeouts).
// This is arbitrary just to not leave the player in an essentially deadlocked state if any connection issues occur.
await Task.WhenAny(resultsReady.Task, Task.Delay(TimeSpan.FromSeconds(60)));
await Task.WhenAny(resultsReady.Task, Task.Delay(TimeSpan.FromSeconds(60))).ConfigureAwait(false);
}
protected override ResultsScreen CreateResults(ScoreInfo score)

View File

@ -108,7 +108,7 @@ namespace osu.Game.Screens.OnlinePlay.Playlists
protected override async Task SubmitScore(Score score)
{
await base.SubmitScore(score);
await base.SubmitScore(score).ConfigureAwait(false);
Debug.Assert(Token != null);
@ -128,7 +128,7 @@ namespace osu.Game.Screens.OnlinePlay.Playlists
};
api.Queue(request);
await tcs.Task;
await tcs.Task.ConfigureAwait(false);
}
protected override void Dispose(bool isDisposing)

View File

@ -592,7 +592,7 @@ namespace osu.Game.Screens.Play
try
{
await SubmitScore(score);
await SubmitScore(score).ConfigureAwait(false);
}
catch (Exception ex)
{
@ -601,7 +601,7 @@ namespace osu.Game.Screens.Play
try
{
await ImportScore(score);
await ImportScore(score).ConfigureAwait(false);
}
catch (Exception ex)
{

View File

@ -120,7 +120,7 @@ namespace osu.Game.Skinning
protected override async Task Populate(SkinInfo model, ArchiveReader archive, CancellationToken cancellationToken = default)
{
await base.Populate(model, archive, cancellationToken);
await base.Populate(model, archive, cancellationToken).ConfigureAwait(false);
if (model.Name?.Contains(".osk") == true)
populateMetadata(model);

View File

@ -136,7 +136,7 @@ namespace osu.Game.Tests.Visual.Multiplayer
{
Debug.Assert(Room != null);
await ((IMultiplayerClient)this).SettingsChanged(settings);
await ((IMultiplayerClient)this).SettingsChanged(settings).ConfigureAwait(false);
foreach (var user in Room.Users.Where(u => u.State == MultiplayerUserState.Ready))
ChangeUserState(user.UserID, MultiplayerUserState.Idle);

View File

@ -37,7 +37,7 @@ namespace osu.Game.Updater
{
var releases = new OsuJsonWebRequest<GitHubRelease>("https://api.github.com/repos/ppy/osu/releases/latest");
await releases.PerformAsync();
await releases.PerformAsync().ConfigureAwait(false);
var latest = releases.ResponseObject;

View File

@ -69,7 +69,7 @@ namespace osu.Game.Updater
lock (updateTaskLock)
waitTask = (updateCheckTask ??= PerformUpdateCheck());
bool hasUpdates = await waitTask;
bool hasUpdates = await waitTask.ConfigureAwait(false);
lock (updateTaskLock)
updateCheckTask = null;