Skip to content

Code Quality: Introduced a wrapper for non-blocking await on a sync method #17100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Files.App.CsWin32/NativeMethods.txt
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
GetKeyState
CreateDirectoryFromApp
WNetCancelConnection2
NET_USE_CONNECT_FLAGS

Check warning on line 48 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Debug, arm64)

Method, type or constant "NET_USE_CONNECT_FLAGS" not found

Check warning on line 48 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Release, x64)

Method, type or constant "NET_USE_CONNECT_FLAGS" not found

Check warning on line 48 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Release, arm64)

Method, type or constant "NET_USE_CONNECT_FLAGS" not found

Check warning on line 48 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Debug, x64)

Method, type or constant "NET_USE_CONNECT_FLAGS" not found
NETRESOURCEW
WNetAddConnection3
CREDENTIALW
Expand Down Expand Up @@ -78,7 +78,7 @@
SetEntriesInAcl
ACL_SIZE_INFORMATION
DeleteAce
EXPLICIT_ACCESS

Check warning on line 81 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Debug, arm64)

Method, type or constant "EXPLICIT_ACCESS" not found. Did you mean or "EXPLICIT_ACCESS_A" or "EXPLICIT_ACCESS_W"?

Check warning on line 81 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Release, x64)

Method, type or constant "EXPLICIT_ACCESS" not found. Did you mean or "EXPLICIT_ACCESS_A" or "EXPLICIT_ACCESS_W"?

Check warning on line 81 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Release, arm64)

Method, type or constant "EXPLICIT_ACCESS" not found. Did you mean or "EXPLICIT_ACCESS_A" or "EXPLICIT_ACCESS_W"?

Check warning on line 81 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Debug, x64)

Method, type or constant "EXPLICIT_ACCESS" not found. Did you mean or "EXPLICIT_ACCESS_A" or "EXPLICIT_ACCESS_W"?
ACCESS_ALLOWED_ACE
LookupAccountSid
GetComputerName
Expand Down Expand Up @@ -134,7 +134,7 @@
CoTaskMemFree
QueryDosDevice
DeviceIoControl
GetLastError

Check warning on line 137 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Debug, arm64)

This API will not be generated. Do not generate GetLastError. Call Marshal.GetLastWin32Error() instead. Learn more from https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.marshal.getlastwin32error

Check warning on line 137 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Release, x64)

This API will not be generated. Do not generate GetLastError. Call Marshal.GetLastWin32Error() instead. Learn more from https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.marshal.getlastwin32error

Check warning on line 137 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Release, arm64)

This API will not be generated. Do not generate GetLastError. Call Marshal.GetLastWin32Error() instead. Learn more from https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.marshal.getlastwin32error

Check warning on line 137 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Debug, x64)

This API will not be generated. Do not generate GetLastError. Call Marshal.GetLastWin32Error() instead. Learn more from https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.marshal.getlastwin32error
CreateFile
GetVolumeInformation
COMPRESSION_FORMAT
Expand Down Expand Up @@ -226,3 +226,8 @@
RoGetAgileReference
IQueryInfo
QITIPF_FLAGS
CreateEvent
SetEvent
CoWaitForMultipleObjects
CWMO_FLAGS
INFINITE
44 changes: 44 additions & 0 deletions src/Files.App.Storage/Storables/WindowsStorage/STATask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
// Licensed under the MIT License.

using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.System.Com;
using Windows.Win32.Security;

namespace Files.App.Storage
{
Expand Down Expand Up @@ -143,5 +146,46 @@ public static Task Run(Func<Task> func)

return tcs.Task;
}

public unsafe static Task RunAsSync(Action action)
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() is ApartmentState.STA);

HANDLE hEventHandle = PInvoke.CreateEvent((SECURITY_ATTRIBUTES*)null, true, false, default);

var tcs = new TaskCompletionSource();

Task.Run(() =>
{
try
{
action();
tcs.SetResult();
}
catch (Exception ex)
{
tcs.SetException(ex);
}
finally
{
PInvoke.SetEvent(hEventHandle);
}
});

HANDLE* pEventHandles = stackalloc HANDLE[1];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you even need to allocate a stack here? I thought your HANDLE variable is in stack already.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Related to your 2nd comment, it looks like you can't take address of a local variable that goes thru an async lambda/function. The current code doesn't have async and initially did so this can be refactored but IIUC if we wanna use async void we may have to do this.

pEventHandles[0] = hEventHandle;
uint dwIndex = 0u;

PInvoke.CoWaitForMultipleObjects(
(uint)CWMO_FLAGS.CWMO_DEFAULT,
PInvoke.INFINITE,
1u,
pEventHandles,
&dwIndex);

PInvoke.CloseHandle(hEventHandle);

return tcs.Task;
}
}
}
14 changes: 0 additions & 14 deletions src/Files.App/Helpers/Win32/Win32PInvoke.Methods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,6 @@ public static extern int GetDpiForWindow(
IntPtr hwnd
);

[DllImport("ole32.dll")]
public static extern uint CoWaitForMultipleObjects(
uint dwFlags,
uint dwMilliseconds,
ulong nHandles,
IntPtr[] pHandles,
out uint dwIndex
);

[DllImport("shell32.dll")]
public static extern IntPtr SHBrowseForFolder(
ref BROWSEINFO lpbi
Expand Down Expand Up @@ -135,11 +126,6 @@ public static extern uint WaitForMultipleObjectsEx(
bool bAlertable
);

[DllImport("api-ms-win-core-synch-l1-2-0.dll", SetLastError = true)]
public static extern bool ResetEvent(
IntPtr hEvent
);

[DllImport("api-ms-win-core-synch-l1-2-0.dll", SetLastError = true)]
public static extern uint WaitForSingleObjectEx(
IntPtr hHandle,
Expand Down
28 changes: 2 additions & 26 deletions src/Files.App/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using System.Text;
using Windows.ApplicationModel.Activation;
using Windows.Storage;
using static Files.App.Helpers.Win32PInvoke;

namespace Files.App
{
Expand All @@ -21,9 +20,6 @@ namespace Files.App
/// </remarks>
internal sealed class Program
{
private const uint CWMO_DEFAULT = 0;
private const uint INFINITE = 0xFFFFFFFF;

public static Semaphore? Pool { get; set; }

static Program()
Expand Down Expand Up @@ -250,20 +246,10 @@ private static async void OnActivated(object? sender, AppActivationArguments arg
/// </remarks>
public static void RedirectActivationTo(AppInstance keyInstance, AppActivationArguments args)
{
IntPtr eventHandle = CreateEvent(IntPtr.Zero, true, false, null);

Task.Run(() =>
STATask.RunAsSync(() =>
{
keyInstance.RedirectActivationToAsync(args).AsTask().Wait();
SetEvent(eventHandle);
});

_ = CoWaitForMultipleObjects(
CWMO_DEFAULT,
INFINITE,
1,
[eventHandle],
out uint handleIndex);
}

public static void OpenShellCommandInExplorer(string shellCommand, int pid)
Expand All @@ -273,20 +259,10 @@ public static void OpenShellCommandInExplorer(string shellCommand, int pid)

public static void OpenFileFromTile(string filePath)
{
IntPtr eventHandle = CreateEvent(IntPtr.Zero, true, false, null);

Task.Run(() =>
STATask.RunAsSync(() =>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason why async void isn't desirable here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So you mean adding Wait() in that helper method instead?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean making it an async lambda and then await.

{
LaunchHelper.LaunchAppAsync(filePath, null, null).Wait();
SetEvent(eventHandle);
});

_ = CoWaitForMultipleObjects(
CWMO_DEFAULT,
INFINITE,
1,
[eventHandle],
out uint handleIndex);
}
}
}
Loading