在新线程上创建类的实例

st_*_*nov -1 c# winforms

我正在创建一个位于 DLL 中且无法修改的类的实例。它加载图像需要很长时间,这会冻结 WinForms UI。

我可以在新线程上实例化该类吗?

var images = new AppImages(); // This to execute on new thread?
var cboData = new List<string>();
foreach(var image in images)
{
    cboData.Add(image); 
}
comboBox.DataSource = cboData;
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用

private void My()
{
    var images = ThreadPool.QueueUserWorkItem(GetAppImages);
     
    var cboData = new List<string>();
    foreach(var image in images)
    {
        cboData.Add(image); 
    }
    comboBox.DataSource = cboData;
}

private AppImages GetAppImages()
{
    return new AppImages();
}
Run Code Online (Sandbox Code Playgroud)

但 threadPool 不返回任何值,它只是执行代码,我需要新实例稍后在代码中使用它。

另外,我可以在新线程中调用整个逻辑,因为存在 UI 元素(例如组合框)。

Jon*_*eet 8

我建议使用在不同的线程中Task.Run进行初始化AppImages,并从 UI 线程等待该任务。所以:

public async Task My()
{
    Task<AppImages> task = Task.Run(() => new AppImages());
    var images = await task;
    comboBox.DataSource = images.Images.ToList();
}
Run Code Online (Sandbox Code Playgroud)

此处的使用await意味着该方法的最后一行仍然在 UI 线程上运行 - 但在任务运行时它不会阻塞 UI。