Skip to content

Code Quality: Replaced the StartSTA helpers with STATask.Run #17377

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

Merged
merged 1 commit into from
Aug 1, 2025
Merged
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
4 changes: 2 additions & 2 deletions src/Files.App/Helpers/Win32/Win32Helper.Shell.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static partial class Win32Helper
path = $"shell:{path}";
}

return await Win32Helper.StartSTATask(() =>
return await STATask.Run(() =>
{
var flc = new List<ShellFileItem>();
var folder = (ShellFileItem)null;
Expand Down Expand Up @@ -77,7 +77,7 @@ public static partial class Win32Helper
}

return (folder, flc);
});
}, App.Logger);
}

public static string GetFolderFromKnownFolderGUID(Guid guid)
Expand Down
137 changes: 0 additions & 137 deletions src/Files.App/Helpers/Win32/Win32Helper.Storage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,143 +26,6 @@ namespace Files.App.Helpers
/// </summary>
public static partial class Win32Helper
{
public static Task StartSTATask(Func<Task> func)
{
var taskCompletionSource = new TaskCompletionSource();
Thread thread = new Thread(async () =>
{
Ole32.OleInitialize();

try
{
await func();
taskCompletionSource.SetResult();
}
catch (Exception ex)
{
taskCompletionSource.SetResult();
App.Logger.LogWarning(ex, ex.Message);
}
finally
{
Ole32.OleUninitialize();
}
})

{
IsBackground = true,
Priority = ThreadPriority.Normal
};

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

return taskCompletionSource.Task;
}

public static Task StartSTATask(Action action)
{
var taskCompletionSource = new TaskCompletionSource();
Thread thread = new Thread(() =>
{
Ole32.OleInitialize();

try
{
action();
taskCompletionSource.SetResult();
}
catch (Exception ex)
{
taskCompletionSource.SetResult();
App.Logger.LogWarning(ex, ex.Message);
}
finally
{
Ole32.OleUninitialize();
}
})

{
IsBackground = true,
Priority = ThreadPriority.Normal
};

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

return taskCompletionSource.Task;
}

public static Task<T?> StartSTATask<T>(Func<T> func)
{
var taskCompletionSource = new TaskCompletionSource<T?>();

Thread thread = new Thread(() =>
{
Ole32.OleInitialize();

try
{
taskCompletionSource.SetResult(func());
}
catch (Exception ex)
{
taskCompletionSource.SetResult(default);
App.Logger.LogWarning(ex, ex.Message);
//tcs.SetException(e);
}
finally
{
Ole32.OleUninitialize();
}
})

{
IsBackground = true,
Priority = ThreadPriority.Normal
};

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

return taskCompletionSource.Task;
}

public static Task<T?> StartSTATask<T>(Func<Task<T>> func)
{
var taskCompletionSource = new TaskCompletionSource<T?>();

Thread thread = new Thread(async () =>
{
Ole32.OleInitialize();
try
{
taskCompletionSource.SetResult(await func());
}
catch (Exception ex)
{
taskCompletionSource.SetResult(default);
App.Logger.LogInformation(ex, ex.Message);
//tcs.SetException(e);
}
finally
{
Ole32.OleUninitialize();
}
})

{
IsBackground = true,
Priority = ThreadPriority.Normal
};

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

return taskCompletionSource.Task;
}

public static async Task<string?> GetFileAssociationAsync(string filename, bool checkDesktopFirst = false)
{
// Find UWP apps
Expand Down
8 changes: 4 additions & 4 deletions src/Files.App/Services/Storage/StorageNetworkService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public async Task<IEnumerable<IFolder>> GetComputersAsync()
/// <inheritdoc/>
public async Task<IEnumerable<IFolder>> GetShortcutsAsync()
{
var networkLocations = await Win32Helper.StartSTATask(() =>
var networkLocations = await STATask.Run(() =>
{
var locations = new List<ShellLinkItem>();
using (var netHood = new ShellFolder(Shell32.KNOWNFOLDERID.FOLDERID_NetHood))
Expand All @@ -114,7 +114,7 @@ public async Task<IEnumerable<IFolder>> GetShortcutsAsync()
}
}
return locations;
});
}, App.Logger);

return (networkLocations ?? Enumerable.Empty<ShellLinkItem>()).Select(item =>
{
Expand Down Expand Up @@ -192,13 +192,13 @@ public bool DisconnectNetworkDrive(IFolder drive)
/// <inheritdoc/>
public Task OpenMapNetworkDriveDialogAsync()
{
return Win32Helper.StartSTATask(() =>
return STATask.Run(() =>
{
return CommonDialogService.Open_NetworkConnectionDialog(
MainWindow.Instance.WindowHandle,
useMostRecentPath: true,
hideRestoreConnectionCheckBox: false);
});
}, App.Logger);
}

/// <inheritdoc/>
Expand Down
4 changes: 2 additions & 2 deletions src/Files.App/Services/Storage/StorageTrashBinService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public bool EmptyTrashBin()
/// <inheritdoc/>
public async Task<bool> RestoreAllTrashesAsync()
{
return await Win32Helper.StartSTATask(() =>
return await STATask.Run(() =>
{
try
{
Expand All @@ -95,7 +95,7 @@ public async Task<bool> RestoreAllTrashesAsync()
{
return false;
}
});
}, App.Logger);
}

private unsafe bool RestoreAllTrashesInternal()
Expand Down
8 changes: 4 additions & 4 deletions src/Files.App/Services/Windows/WindowsQuickAccessService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,20 +63,20 @@ private async Task UnpinFromSidebarAsync(string[] folderPaths, bool doUpdateQuic
(folderPaths.Contains(path) ||
(path.StartsWith(@"\\SHELL\\") && folderPaths.Any(x => x.StartsWith(@"\\SHELL\\")))))
{
await Win32Helper.StartSTATask(async () =>
await STATask.Run(async () =>
{
fi.InvokeVerb("unpinfromhome");
});
}, App.Logger);
continue;
}
}

if (folderPaths.Contains(pathStr))
{
await Win32Helper.StartSTATask(async () =>
await STATask.Run(async () =>
{
fi.InvokeVerb("unpinfromhome");
});
}, App.Logger);
}
}

Expand Down
12 changes: 6 additions & 6 deletions src/Files.App/Utils/Library/LibraryManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ private void InitializeWatcher()
/// <returns>List of library items</returns>
public static async Task<List<LibraryLocationItem>> ListUserLibraries()
{
var libraries = await Win32Helper.StartSTATask(() =>
var libraries = await STATask.Run(() =>
{
try
{
Expand All @@ -90,7 +90,7 @@ public static async Task<List<LibraryLocationItem>> ListUserLibraries()
}

return [];
});
}, App.Logger);

return libraries.Select(lib => new LibraryLocationItem(lib)).ToList();
}
Expand Down Expand Up @@ -134,7 +134,7 @@ public async Task<bool> CreateNewLibrary(string name)
if (string.IsNullOrWhiteSpace(name) || !CanCreateLibrary(name).result)
return false;

var newLib = new LibraryLocationItem(await Win32Helper.StartSTATask(() =>
var newLib = new LibraryLocationItem(await STATask.Run(() =>
{
try
{
Expand All @@ -150,7 +150,7 @@ public async Task<bool> CreateNewLibrary(string name)
}

return Task.FromResult<ShellLibraryItem>(null);
}));
}, App.Logger));

if (newLib is not null)
{
Expand Down Expand Up @@ -178,7 +178,7 @@ public async Task<LibraryLocationItem> UpdateLibrary(string libraryPath, string
// Nothing to update
return null;

var item = await Win32Helper.StartSTATask(() =>
var item = await STATask.Run(() =>
{
try
{
Expand Down Expand Up @@ -231,7 +231,7 @@ public async Task<LibraryLocationItem> UpdateLibrary(string libraryPath, string
}

return Task.FromResult<ShellLibraryItem>(null);
});
}, App.Logger);

var newLib = item is not null ? new LibraryLocationItem(item) : null;
if (newLib is not null)
Expand Down
8 changes: 4 additions & 4 deletions src/Files.App/Utils/Shell/LaunchHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ private static async Task<bool> HandleApplicationLaunch(string application, stri
{
try
{
var opened = await Win32Helper.StartSTATask(async () =>
var opened = await STATask.Run(async () =>
{
var split = application.Split('|').Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => GetMtpPath(x));
if (split.Count() == 1)
Expand Down Expand Up @@ -171,21 +171,21 @@ private static async Task<bool> HandleApplicationLaunch(string application, stri
}

return true;
});
}, App.Logger);

if (!opened)
{
if (application.StartsWith(@"\\SHELL\", StringComparison.Ordinal))
{
opened = await Win32Helper.StartSTATask(async () =>
opened = await STATask.Run(async () =>
{
using var cMenu = await ContextMenu.GetContextMenuForFiles(new[] { application }, PInvoke.CMF_DEFAULTONLY);

if (cMenu is not null)
await cMenu.InvokeItem(cMenu.Items.FirstOrDefault()?.ID ?? -1);

return true;
});
}, App.Logger);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/Files.App/Utils/Storage/Helpers/FileThumbnailHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public static class FileThumbnailHelper
{
var size = iconOptions.HasFlag(IconOptions.UseCurrentScale) ? requestedSize * App.AppModel.AppWindowDPI : requestedSize;

return await Win32Helper.StartSTATask(() => Win32Helper.GetIcon(path, (int)size, isFolder, iconOptions));
return await STATask.Run(() => Win32Helper.GetIcon(path, (int)size, isFolder, iconOptions), App.Logger);
}

/// <summary>
Expand All @@ -24,7 +24,7 @@ public static class FileThumbnailHelper
/// <param name="isFolder"></param>
/// <returns></returns>
public static async Task<byte[]?> GetIconOverlayAsync(string path, bool isFolder)
=> await Win32Helper.StartSTATask(() => Win32Helper.GetIconOverlay(path, isFolder));
=> await STATask.Run(() => Win32Helper.GetIconOverlay(path, isFolder), App.Logger);

[Obsolete]
public static async Task<byte[]?> LoadIconFromPathAsync(string filePath, uint thumbnailSize, ThumbnailMode thumbnailMode, ThumbnailOptions thumbnailOptions, bool isFolder = false)
Expand Down
Loading
Loading