c# - 在分离线程问题中初始化存储库

标签 c# multithreading winforms

在 MainForm.cs 中,我正在初始化一些东西(IBookRepository 和 IDocumentStore)。

private IDocumentStore _store = new EmbeddableDocumentStore {RunInMemory = false };
private IBookRepository _repository;
public MainForm()
{
    InitializeComponent();
    _store.Initialize();
    _repository = new RavenDbBookRepository(_store);
}

由于可嵌入文档存储需要一段时间(5,6 秒)才能初始化,因此我想将其初始化移到单独的线程上

所以我尝试了

 private void InitOnNewThread()
    {
        _store.Initialize();
        _repository = new RavenDbBookRepository(_Store);            
    }

public MainForm()
{
    InitializeComponent();
    Thread t = new Thread(new ThreadStart(InitOnNewThread));
    t.Start();
}

但在主线程内使用此_repository为空,原因是在单独的线程中填充。

因为这是我第一次尝试使用线程,所以我不知道如何克服这个问题。\

你会怎么做?

最佳答案

使用新的 asyncawait 关键字。

public class MainForm : Form
{
  private IDocumentStore _store = new EmbeddableDocumentStore {RunInMemory = false };
  private IBookRepository _repository;

  private async void MainForm_Load(object sender, EventArgs args)
  {
    // Do stuff here that does not depend on _store or _repository.
    await InitializeRepositoryAsync();
    // Now you can use _store and _repository here.
  }

  private Task InitializeRepositoryAsync()
  {
    return Task.Run(
      () =>
      {
        _store.Initialize();
        _repository = new RavenDbBookRepository(_store);
      };
  }
}

await 工作原理的巧妙之处在于,当任务在后台异步运行时,它会抢占 MainForm_Load 的执行。任务完成后,MainForm_Load 的剩余部分将被注入(inject)回 UI 线程的执行流中。它的工作原理确实非常聪明,并且是一个非常优雅的解决方案。

关于c# - 在分离线程问题中初始化存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19587670/

相关文章:

c# - 随机化 3 种颜色

c# - 将所有打开的窗口从任何进程移动到主屏幕的中心

c# - 如何在 C# 中将日期时间转换为日期

java - 为什么Java虚拟机中没有GIL?为什么 Python 这么需要一个?

java - 并发读取共享对象中的只读字段并写入读/写字段

android - 从线程更改 TextView 文本

.net - 对 CheckedListbox 进行自然排序

C# Blazor客户端从url中读取hash参数

c# - 在控制台应用程序的不同线程中运行任务

c# - 无法打开,因为是852版本,本服务器支持782及更早版本