是否可以在 C# 中等待线程

Is it possible to await Thread in C#

我处于必须手动生成新线程的情况,因此我可以调用 .SetApartmentState(ApartmentState.STA)。这意味着(据我所知)我不能使用 Task。但我想知道线程何时完成 运行,类似于与 async 一起使用的 await。然而,我能想出的最好办法是循环,不断检查 Thread.IsAlive,像这样:

var thread = new Thread(() =>
{ 
    // my code here 
});

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

while(thread.IsAlive)
{
    // Wait 100 ms
    Thread.Sleep(100);
}

这应该可行(只要线程不会停止),但它看起来有点笨拙。有没有更聪明的方法来检查线程何时完成(或死亡)?

这只是为了避免阻塞 GUI 线程,所以任何轻微的性能影响都没有问题(比如几百毫秒)。

这是一个扩展方法,您可以使用它来启用线程等待(灵感来自这篇文章:await anything)。

public static TaskAwaiter GetAwaiter(this Thread thread)
{
    return Task.Run(async () =>
    {
        while (thread.IsAlive)
        {
            await Task.Delay(100).ConfigureAwait(false);
        }
    }).GetAwaiter();
}

用法示例:

var thread = new Thread(() =>
{ 
    Thread.Sleep(1000); // Simulate some background work
});
thread.IsBackground = true;
thread.Start();
await thread; // Wait asynchronously until the thread is completed
thread.Join(); // If you want to be extra sure that the thread has finished

可以使用 BackgroundWorker class 吗?它有一个在完成时报告的事件。