Skip to content

Commit

Permalink
Dialog enqueued block
Browse files Browse the repository at this point in the history
  • Loading branch information
Lightczx committed Sep 12, 2024
1 parent da6e621 commit 5ca7652
Show file tree
Hide file tree
Showing 18 changed files with 37 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,7 @@ public string DestinationFilePath
}
}

public SafeFileHandle DestinationFileHandle
{
get
{
return destinationFileHandle ??= GetFileHandle();
}
}
public SafeFileHandle DestinationFileHandle { get => destinationFileHandle ??= GetFileHandle(); }

public long ContentLength
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ namespace Snap.Hutao.Core.Threading;

internal static class SemaphoreSlimExtension
{
[Obsolete("Use AsyncLock instead")]
public static async ValueTask<SemaphoreSlimToken> EnterAsync(this SemaphoreSlim semaphoreSlim, CancellationToken token = default)
{
try
Expand All @@ -22,7 +21,6 @@ public static async ValueTask<SemaphoreSlimToken> EnterAsync(this SemaphoreSlim
return new SemaphoreSlimToken(semaphoreSlim);
}

[Obsolete("Use AsyncLock instead")]
public static SemaphoreSlimToken Enter(this SemaphoreSlim semaphoreSlim)
{
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public bool IsDialogShowing
}
}

public ITaskContext TaskContext { get => taskContext; }

public async ValueTask<ContentDialogResult> CreateForConfirmAsync(string title, string content)
{
await taskContext.SwitchToMainThreadAsync();
Expand Down Expand Up @@ -108,20 +110,22 @@ public TContentDialog CreateInstance<TContentDialog>(params object[] parameters)

[SuppressMessage("", "SH003")]
[SuppressMessage("", "SH100")]
public Task<ContentDialogResult> EnqueueAndShowAsync(Microsoft.UI.Xaml.Controls.ContentDialog contentDialog)
public Task<ContentDialogResult> EnqueueAndShowAsync(Microsoft.UI.Xaml.Controls.ContentDialog contentDialog, TaskCompletionSource? dialogShowSource = default)
{
TaskCompletionSource<ContentDialogResult> dialogShowCompletionSource = new();
TaskCompletionSource<ContentDialogResult> dialogResultSource = new();

dialogQueue.Enqueue(async () =>
{
try
{
await taskContext.SwitchToMainThreadAsync();
dialogShowSource?.TrySetResult();
ContentDialogResult result = await contentDialog.ShowAsync();
dialogShowCompletionSource.SetResult(result);
dialogResultSource.SetResult(result);
}
catch (Exception ex)
{
dialogShowCompletionSource.SetException(ex);
dialogResultSource.SetException(ex);
}
finally
{
Expand All @@ -134,7 +138,7 @@ public Task<ContentDialogResult> EnqueueAndShowAsync(Microsoft.UI.Xaml.Controls.
ShowNextDialog();
}

return dialogShowCompletionSource.Task;
return dialogResultSource.Task;

Task ShowNextDialog()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ internal interface IContentDialogFactory
{
bool IsDialogShowing { get; }

ITaskContext TaskContext { get; }

/// <summary>
/// 异步确认
/// </summary>
Expand Down Expand Up @@ -44,5 +46,5 @@ ValueTask<TContentDialog> CreateInstanceAsync<TContentDialog>(params object[] pa
where TContentDialog : Microsoft.UI.Xaml.Controls.ContentDialog;

[SuppressMessage("", "SH003")]
Task<ContentDialogResult> EnqueueAndShowAsync(Microsoft.UI.Xaml.Controls.ContentDialog contentDialog);
Task<ContentDialogResult> EnqueueAndShowAsync(Microsoft.UI.Xaml.Controls.ContentDialog contentDialog, TaskCompletionSource? dialogShowSource = default);
}
15 changes: 0 additions & 15 deletions src/Snap.Hutao/Snap.Hutao/Service/AvatarInfo/AvatarInfoService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@
using Snap.Hutao.Service.Metadata;
using Snap.Hutao.ViewModel.AvatarProperty;
using Snap.Hutao.ViewModel.User;
using Snap.Hutao.Web.Enka;
using Snap.Hutao.Web.Enka.Model;
using Snap.Hutao.Web.Hoyolab;
using EntityAvatarInfo = Snap.Hutao.Model.Entity.AvatarInfo;

namespace Snap.Hutao.Service.AvatarInfo;
Expand All @@ -20,7 +17,6 @@ internal sealed partial class AvatarInfoService : IAvatarInfoService
{
private readonly AvatarInfoRepositoryOperation avatarInfoDbBulkOperation;
private readonly IAvatarInfoRepository avatarInfoRepository;
private readonly IServiceScopeFactory serviceScopeFactory;
private readonly ILogger<AvatarInfoService> logger;
private readonly IMetadataService metadataService;
private readonly ISummaryFactory summaryFactory;
Expand Down Expand Up @@ -50,17 +46,6 @@ internal sealed partial class AvatarInfoService : IAvatarInfoService
}
}

private async ValueTask<EnkaResponse?> GetEnkaResponseAsync(PlayerUid uid, CancellationToken token = default)
{
using (IServiceScope scope = serviceScopeFactory.CreateScope())
{
EnkaClient enkaClient = scope.ServiceProvider.GetRequiredService<EnkaClient>();

return await enkaClient.GetForwardDataAsync(uid, token).ConfigureAwait(false)
?? await enkaClient.GetDataAsync(uid, token).ConfigureAwait(false);
}
}

private async ValueTask<Summary> GetSummaryCoreAsync(IEnumerable<EntityAvatarInfo> avatarInfos, CancellationToken token)
{
using (ValueStopwatch.MeasureExecution(logger))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ public async ValueTask<GachaArchive> EnsureArchiveInCollectionAsync(Guid archive
// save items for each queryType
token.ThrowIfCancellationRequested();
fetchContext.SaveItems();
await Task.Delay((int)(System.Random.Shared.NextDouble() * (2000 - 1000)) + 1000).ConfigureAwait(false);
await Task.Delay((int)(System.Random.Shared.NextDouble() * (2000 - 1000)) + 1000, token).ConfigureAwait(false);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public async ValueTask OnExecutionAsync(LaunchExecutionContext context, LaunchEx
LaunchGamePackageConvertDialog dialog = await contentDialogFactory.CreateInstanceAsync<LaunchGamePackageConvertDialog>().ConfigureAwait(false);
IProgress<PackageConvertStatus> convertProgress = progressFactory.CreateForMainThread<PackageConvertStatus>(state => dialog.State = state);

using (await dialog.BlockAsync(context.TaskContext).ConfigureAwait(false))
using (await dialog.BlockAsync(contentDialogFactory).ConfigureAwait(false))
{
if (!await EnsureGameResourceAsync(context, gameFileSystem, convertProgress).ConfigureAwait(false))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@

namespace Snap.Hutao.Service.Navigation;

/// <summary>
/// 表示导航等待器
/// </summary>
[HighQuality]
internal interface INavigationAwaiter
{
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license.

using Microsoft.UI.Xaml.Controls;
using Snap.Hutao.Factory.ContentDialog;

namespace Snap.Hutao.UI.Xaml.Control;

Expand All @@ -17,6 +18,8 @@ internal static class ContentDialogExtension
/// <param name="contentDialog">对话框</param>
/// <param name="taskContext">任务上下文</param>
/// <returns>用于恢复用户交互</returns>
[Obsolete("Use another overload")]
[SuppressMessage("", "SH100")]
public static async ValueTask<ContentDialogScope> BlockAsync(this ContentDialog contentDialog, ITaskContext taskContext)
{
await taskContext.SwitchToMainThreadAsync();
Expand All @@ -26,4 +29,12 @@ public static async ValueTask<ContentDialogScope> BlockAsync(this ContentDialog
_ = contentDialog.ShowAsync();
return new ContentDialogScope(contentDialog, taskContext);
}

public static async ValueTask<ContentDialogScope> BlockAsync(this ContentDialog contentDialog, IContentDialogFactory contentDialogFactory)
{
TaskCompletionSource dialogShowSource = new();
_ = contentDialogFactory.EnqueueAndShowAsync(contentDialog, dialogShowSource);
await dialogShowSource.Task.ConfigureAwait(false);
return new ContentDialogScope(contentDialog, contentDialogFactory.TaskContext);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ private async ValueTask<bool> TryImportCoreAsync(AchievementViewModelScopeContex
.ConfigureAwait(false);

ImportResult result;
using (await dialog.BlockAsync(scopeContext.TaskContext).ConfigureAwait(false))
using (await dialog.BlockAsync(scopeContext.ContentDialogFactory).ConfigureAwait(false))
{
result = await context.AchievementService.ImportFromUIAFAsync(archive, uiaf.List, strategy).ConfigureAwait(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private async Task RefreshCoreAsync(UserAndUid userAndUid, RefreshOption option,
.CreateForIndeterminateProgressAsync(SH.ViewModelAvatarPropertyFetch)
.ConfigureAwait(false);

using (await dialog.BlockAsync(scopeContext.TaskContext).ConfigureAwait(false))
using (await dialog.BlockAsync(scopeContext.ContentDialogFactory).ConfigureAwait(false))
{
summaryResult = await scopeContext.AvatarInfoService
.GetSummaryAsync(userAndUid, option, token)
Expand Down Expand Up @@ -203,7 +203,7 @@ private async Task BatchCultivateAsync()
.ConfigureAwait(false);

BatchCultivateResult result = default;
using (await progressDialog.BlockAsync(scopeContext.TaskContext).ConfigureAwait(false))
using (await progressDialog.BlockAsync(scopeContext.ContentDialogFactory).ConfigureAwait(false))
{
List<CalculatorAvatarPromotionDelta> deltas = [];
foreach (AvatarView avatar in avatars)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ private async Task RefreshInventoryAsync()
.CreateForIndeterminateProgressAsync(SH.ViewModelCultivationRefreshInventoryProgress)
.ConfigureAwait(false);

using (await dialog.BlockAsync(taskContext).ConfigureAwait(false))
using (await dialog.BlockAsync(contentDialogFactory).ConfigureAwait(false))
{
await inventoryService.RefreshInventoryAsync(Projects.CurrentItem).ConfigureAwait(false);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ private async Task TrackCurrentUserAndUidAsync()
.CreateForIndeterminateProgressAsync(SH.ViewModelDailyNoteRequestProgressTitle)
.ConfigureAwait(false);

using (await dialog.BlockAsync(taskContext).ConfigureAwait(false))
using (await dialog.BlockAsync(contentDialogFactory).ConfigureAwait(false))
{
await dailyNoteService.AddDailyNoteAsync(userAndUid).ConfigureAwait(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ private async ValueTask RefreshCoreAsync(RefreshOption option)
ContentDialogScope hideToken;
try
{
hideToken = await dialog.BlockAsync(taskContext).ConfigureAwait(false);
hideToken = await dialog.BlockAsync(contentDialogFactory).ConfigureAwait(false);
}
catch (COMException ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ private async Task UploadAsync(GachaArchive? gachaArchive)
bool isOk;
string message;

using (await dialog.BlockAsync(taskContext).ConfigureAwait(false))
using (await dialog.BlockAsync(contentDialogFactory).ConfigureAwait(false))
{
(isOk, message) = await hutaoCloudService.UploadGachaItemsAsync(gachaArchive).ConfigureAwait(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private async Task ResetStaticResource()
.CreateForIndeterminateProgressAsync(SH.ViewModelSettingResetStaticResourceProgress)
.ConfigureAwait(false);

await using (await dialog.BlockAsync(taskContext).ConfigureAwait(false))
await using (await dialog.BlockAsync(contentDialogFactory).ConfigureAwait(false))
{
await taskContext.SwitchToBackgroundAsync();
StaticResource.FailAll();
Expand Down
2 changes: 1 addition & 1 deletion src/Snap.Hutao/Snap.Hutao/ViewModel/TitleViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ private async ValueTask DoCheckUpdateAsync()
ContentDialog contentDialog = await contentDialogFactory
.CreateForIndeterminateProgressAsync(SH.ViewTitleUpdatePackageInstallingContent)
.ConfigureAwait(false);
using (await contentDialog.BlockAsync(taskContext).ConfigureAwait(false))
using (await contentDialog.BlockAsync(contentDialogFactory).ConfigureAwait(false))
{
if (launchUpdaterResult.Process is { } updater)
{
Expand Down
5 changes: 2 additions & 3 deletions src/Snap.Hutao/Snap.Hutao/Web/Bridge/MiHoYoJSBridgeFacade.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
namespace Snap.Hutao.Web.Bridge;

[HighQuality]
[SuppressMessage("", "CA1001")]
internal class MiHoYoJSBridgeFacade
{
private const string InitializeJsInterfaceScript = """
Expand Down Expand Up @@ -76,7 +75,7 @@ function mouseListener (e, event) {
document.addEventListener('mousedown', mouseDownListener);
""";

private readonly SemaphoreSlim webMessageSemaphore = new(1);
private readonly AsyncLock webMessageLock = new();
private readonly Guid bridgeId = Guid.NewGuid();
private readonly UserAndUid userAndUid;

Expand Down Expand Up @@ -406,7 +405,7 @@ private async void OnWebMessageReceived(CoreWebView2 webView2, CoreWebView2WebMe

ArgumentNullException.ThrowIfNull(param);
logger.LogInformation("[OnMessage]\nMethod : {method}\nPayload : {payload}\nCallback: {callback}", param.Method, param.Payload, param.Callback);
using (await webMessageSemaphore.EnterAsync().ConfigureAwait(false))
using (await webMessageLock.LockAsync().ConfigureAwait(false))
{
IJsBridgeResult? result = await TryGetJsResultFromJsParamAsync(param).ConfigureAwait(false);

Expand Down

0 comments on commit 5ca7652

Please sign in to comment.