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

标签 c# multithreading sta

我处于必须手动生成新线程的情况,因此我可以调用 .SetApartmentState(ApartmentState.STA)。这意味着(据我所知)我不能使用 Task。但我想知道线程何时完成运行,例如 awaitasync 一起使用。然而,我能想出的最好办法是循环,不断检查 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

关于c# - 是否可以在 C# 中等待线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58866504/

相关文章:

c# - 是否有 Hilbert-Huang 变换的 .Net(首选 F# 或 C#)实现?

java - 如果 Web 服务器已经创建了线程,为什么还要手动创建线程?

c# - 来自外部进程的 C# 中的线程问题

.net - 这种情况下需要STA消息循环吗?

c# - 为什么 Task.Delay 会破坏线程的 STA 状态?

c# - Windows 工具提示未显示

c# DateTime,修剪而不转换为字符串

c# - Azure ServiceBus 消息序列化/反序列化

c# - 如果线程花费太长时间,如何停止线程

c++ - 将参数从主线程传递到线程。当线程退出时,主线程重置为0。为什么?