Skip to content

Commit 2303e6c

Browse files
committed
Init
1 parent 5aa072c commit 2303e6c

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

src/Files.App.CsWin32/NativeMethods.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,3 +225,8 @@ QITIPF_FLAGS
225225
GetKeyboardState
226226
MapVirtualKey
227227
GetKeyboardLayout
228+
CreateEvent
229+
SetEvent
230+
CoWaitForMultipleObjects
231+
CWMO_FLAGS
232+
INFINITE

src/Files.App.Storage/Storables/WindowsStorage/STATask.cs

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
// Licensed under the MIT License.
33

44
using Windows.Win32;
5+
using Windows.Win32.Foundation;
6+
using Windows.Win32.System.Com;
7+
using Windows.Win32.Security;
58

69
namespace Files.App.Storage
710
{
@@ -143,5 +146,60 @@ public static Task Run(Func<Task> func)
143146

144147
return tcs.Task;
145148
}
149+
150+
public static Task<T?> RunAsSync<T>(Func<Task<T>> func)
151+
{
152+
HANDLE hEventHandle = default;
153+
154+
unsafe
155+
{
156+
hEventHandle = PInvoke.CreateEvent((SECURITY_ATTRIBUTES*)null, true, false, default);
157+
}
158+
159+
var tcs = new TaskCompletionSource<T?>();
160+
161+
Thread thread =
162+
new(async () =>
163+
{
164+
PInvoke.OleInitialize();
165+
166+
try
167+
{
168+
tcs.SetResult(await func());
169+
}
170+
catch (Exception ex)
171+
{
172+
tcs.SetException(ex);
173+
}
174+
finally
175+
{
176+
PInvoke.SetEvent(hEventHandle);
177+
PInvoke.OleUninitialize();
178+
}
179+
})
180+
{
181+
IsBackground = true,
182+
Priority = ThreadPriority.Normal
183+
};
184+
185+
thread.SetApartmentState(ApartmentState.STA);
186+
thread.Start();
187+
188+
unsafe
189+
{
190+
HANDLE* pEventHandles = stackalloc HANDLE[1];
191+
pEventHandles[0] = hEventHandle;
192+
uint dwIndex = 0u;
193+
194+
PInvoke.CoWaitForMultipleObjects(
195+
(uint)CWMO_FLAGS.CWMO_DEFAULT,
196+
PInvoke.INFINITE,
197+
1u,
198+
pEventHandles,
199+
&dwIndex);
200+
}
201+
202+
return tcs.Task;
203+
}
146204
}
147205
}

0 commit comments

Comments
 (0)