这并不是任务未被垃圾回收的重复。虽然症状相似。
以下代码为一个控制台应用程序,创建了一个STA线程以供WinForms使用。任务是通过TaskScheduler.FromCurrentSynchronizationContext
获得的自定义任务计划程序发布到该线程中的,此处只是隐式地包装了一个WindowsFormsSynchronizationContext
实例。
根据导致STA线程结束的原因,最后一个任务var terminatorTask = Run(() => Application.ExitThread())
(在WinformsApartment.Dispose
方法中调度)可能并没有总是有机会执行。尽管如此,我认为这个任务仍然应该被垃圾回收,但它没有。为什么?
下面是一个自包含的示例,演示了这一点(在.NET 4.8上进行测试,调试和发布都是s_debugTaskRef.IsAlive
为true
):
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConsoleTest
{
class Program
{
// entry point
static async Task Main(string[] args)
{
try
{
using (var apartment = new WinformsApartment(() => new Form()))
{
await Task.Delay(1000);
await apartment.Run(() => Application.ExitThread());
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Environment.Exit(-1);
}
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
Console.WriteLine($"IsAlive: {WinformsApartment.s_debugTaskRef.IsAlive}");
Console.ReadLine();
}
}
public class WinformsApartment : IDisposable
{
readonly Thread _thread; // the STA thread
readonly TaskScheduler _taskScheduler; // the STA thread's task scheduler
readonly Task _threadEndTask; // to keep track of the STA thread completion
readonly object _lock = new object();
public TaskScheduler TaskScheduler { get { return _taskScheduler; } }
public Task AsTask { get { return _threadEndTask; } }
/// <summary>MessageLoopApartment constructor</summary>
public WinformsApartment(Func<Form> createForm)
{
var schedulerTcs = new TaskCompletionSource<TaskScheduler>();
var threadEndTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
// start an STA thread and gets a task scheduler
_thread = new Thread(_ =>
{
try
{
// handle Application.Idle just once
// to make sure we're inside the message loop
// and the proper synchronization context has been correctly installed
void onIdle(object s, EventArgs e) {
Application.Idle -= onIdle;
// make the task scheduler available
schedulerTcs.SetResult(TaskScheduler.FromCurrentSynchronizationContext());
};
Application.Idle += onIdle;
Application.Run(createForm());
threadEndTcs.TrySetResult(true);
}
catch (Exception ex)
{
threadEndTcs.TrySetException(ex);
}
});
async Task waitForThreadEndAsync()
{
// we use TaskCreationOptions.RunContinuationsAsynchronously
// to make sure thread.Join() won't try to join itself
Debug.Assert(Thread.CurrentThread != _thread);
await threadEndTcs.Task.ConfigureAwait(false);
_thread.Join();
}
_thread.SetApartmentState(ApartmentState.STA);
_thread.IsBackground = true;
_thread.Start();
_taskScheduler = schedulerTcs.Task.Result;
_threadEndTask = waitForThreadEndAsync();
}
// TODO: it's here for debugging leaks
public static readonly WeakReference s_debugTaskRef = new WeakReference(null);
/// <summary>shutdown the STA thread</summary>
public void Dispose()
{
lock(_lock)
{
if (Thread.CurrentThread == _thread)
throw new InvalidOperationException();
if (!_threadEndTask.IsCompleted)
{
// execute Application.ExitThread() on the STA thread
var terminatorTask = Run(() => Application.ExitThread());
s_debugTaskRef.Target = terminatorTask; // TODO: it's here for debugging leaks
_threadEndTask.GetAwaiter().GetResult();
}
}
}
/// <summary>Task.Factory.StartNew wrappers</summary>
public Task Run(Action action, CancellationToken token = default(CancellationToken))
{
return Task.Factory.StartNew(action, token, TaskCreationOptions.None, _taskScheduler);
}
public Task<TResult> Run<TResult>(Func<TResult> action, CancellationToken token = default(CancellationToken))
{
return Task.Factory.StartNew(action, token, TaskCreationOptions.None, _taskScheduler);
}
public Task Run(Func<Task> action, CancellationToken token = default(CancellationToken))
{
return Task.Factory.StartNew(action, token, TaskCreationOptions.None, _taskScheduler).Unwrap();
}
public Task<TResult> Run<TResult>(Func<Task<TResult>> action, CancellationToken token = default(CancellationToken))
{
return Task.Factory.StartNew(action, token, TaskCreationOptions.None, _taskScheduler).Unwrap();
}
}
}
我怀疑这可能是.NET Framework的错误。我目前正在调查,如果我有所发现,我会发布出来,但也许有人可以立即提供解释。
try { ... }
里面的所有代码,也就是using
部分单独移到一个方法中再次测试吗?我只是想排除调试器或Jitter引入的隐藏临时变量导致引用保持活动状态的可能性。 - Lasse V. KarlsenWinformsApartment.Dispose
中的第二个调用将永远不会被安排。因此代表它的任务将一直挂起。 - canton7_threadEndTask
重命名为_completion
,并将属性AsTask
改为Completion
,以便跟随类似 Dataflow 属性的示例。 :-) - Theodor Zoulias