Skip to content

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

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
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static partial class WindowsStorableHelpers
{
HRESULT hr = storable.TryGetThumbnail(size, options, out var thumbnailData).ThrowIfFailedOnDebug();
return thumbnailData;
});
}, null);
}

/// <summary>
Expand Down
40 changes: 31 additions & 9 deletions src/Files.App.Storage/Windows/Managers/STATask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@
namespace Files.App.Storage
{
/// <summary>
/// Represents a synchronous/asynchronous operation on STA.
/// Represents a work scheduled to execute on a STA thread.
/// </summary>
public partial class STATask
{
public static Task Run(Action action, ILogger? logger = null)
/// <summary>
/// Schedules the specified work to execute in a new background thread initialized with STA state.
/// </summary>
/// <param name="action">The work to execute in the STA thread.</param>
/// <param name="logger">A logger to capture any exception that occurs during execution.</param>
/// <returns>A <see cref="Task"/> that represents the work scheduled to execute in the STA thread.</returns>
public static Task Run(Action action, ILogger? logger)
{
var tcs = new TaskCompletionSource();

Expand All @@ -29,7 +35,6 @@ public static Task Run(Action action, ILogger? logger = null)
{
tcs.SetResult();
logger?.LogWarning(ex, "An exception was occurred during the execution within STA.");
tcs.SetException(ex);
}
finally
{
Expand All @@ -44,7 +49,14 @@ public static Task Run(Action action, ILogger? logger = null)
return tcs.Task;
}

public static Task<T> Run<T>(Func<T> func, ILogger? logger = null)
/// <summary>
/// Schedules the specified work to execute in a new background thread initialized with STA state.
/// </summary>
/// <typeparam name="T">The type of the result returned by the function.</typeparam>
/// <param name="func">The work to execute in the STA thread.</param>
/// <param name="logger">A logger to capture any exception that occurs during execution.</param>
/// <returns>A <see cref="Task"/> that represents the work scheduled to execute in the STA thread.</returns>
public static Task<T> Run<T>(Func<T> func, ILogger? logger)
{
var tcs = new TaskCompletionSource<T>();

Expand All @@ -61,7 +73,6 @@ public static Task<T> Run<T>(Func<T> func, ILogger? logger = null)
{
tcs.SetResult(default!);
logger?.LogWarning(ex, "An exception was occurred during the execution within STA.");
tcs.SetException(ex);
}
finally
{
Expand All @@ -76,7 +87,13 @@ public static Task<T> Run<T>(Func<T> func, ILogger? logger = null)
return tcs.Task;
}

public static Task Run(Func<Task> func, ILogger? logger = null)
/// <summary>
/// Schedules the specified work to execute in a new background thread initialized with STA state.
/// </summary>
/// <param name="func">The work to execute in the STA thread.</param>
/// <param name="logger">A logger to capture any exception that occurs during execution.</param>
/// <returns>A <see cref="Task"/> that represents the work scheduled to execute in the STA thread.</returns>
public static Task Run(Func<Task> func, ILogger? logger)
{
var tcs = new TaskCompletionSource();

Expand All @@ -94,7 +111,6 @@ public static Task Run(Func<Task> func, ILogger? logger = null)
{
tcs.SetResult();
logger?.LogWarning(ex, "An exception was occurred during the execution within STA.");
tcs.SetException(ex);
}
finally
{
Expand All @@ -109,7 +125,14 @@ public static Task Run(Func<Task> func, ILogger? logger = null)
return tcs.Task;
}

public static Task<T?> Run<T>(Func<Task<T>> func, ILogger? logger = null)
/// <summary>
/// Schedules the specified work to execute in a new background thread initialized with STA state.
/// </summary>
/// <typeparam name="T">The type of the result returned by the function.</typeparam>
/// <param name="func">The work to execute in the STA thread.</param>
/// <param name="logger">A logger to capture any exception that occurs during execution.</param>
/// <returns>A <see cref="Task"/> that represents the work scheduled to execute in the STA thread.</returns>
public static Task<T?> Run<T>(Func<Task<T>> func, ILogger? logger)
{
var tcs = new TaskCompletionSource<T?>();

Expand All @@ -126,7 +149,6 @@ public static Task Run(Func<Task> func, ILogger? logger = null)
{
tcs.SetResult(default);
logger?.LogWarning(ex, "An exception was occurred during the execution within STA.");
tcs.SetException(ex);
}
finally
{
Expand Down
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
Loading
Loading