在单独的线程问题中初始化存储库 [英] initializing repository in separated thread issue
问题描述
在MainForm.cs内部,我正在初始化几件事(IBookRepository和IDocumentStore).
Inside MainForm.cs I'm initializing couple of things (IBookRepository and IDocumentStore).
private IDocumentStore _store = new EmbeddableDocumentStore {RunInMemory = false };
private IBookRepository _repository;
public MainForm()
{
InitializeComponent();
_store.Initialize();
_repository = new RavenDbBookRepository(_store);
}
因为可嵌入文档存储需要一段时间(5.6秒)才能启动,所以我想将其初始化移到单独的线程上
since embeddable document store takes a while (5,6 sec) to init I want to move it's initialization on separate thread
所以我尝试了
private void InitOnNewThread()
{
_store.Initialize();
_repository = new RavenDbBookRepository(_Store);
}
public MainForm()
{
InitializeComponent();
Thread t = new Thread(new ThreadStart(InitOnNewThread));
t.Start();
}
但是在主线程中使用此_repository为空,原因是在单独的线程中填充的.
but using this _repository is null inside main thread, cause is populated in separate thread.
由于这是我第一次尝试使用线程,所以我看不出如何克服这个问题.\
Since this is first time I trying to work with thread I don't see how to overcome this.\
你会怎么做?
推荐答案
使用新的async
和await
关键字.
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
的其余部分将重新注入到UI线程的执行流中.这是非常聪明的,它是如何工作的,并提供了一个非常优雅的解决方案.
The neat thing about how await
works is that it will preempt the execution of MainForm_Load
while the task is running asynchronously in the background. After the task completes the remaining portion of MainForm_Load
will be injected back into the execution stream of the UI thread. It is really quite clever how this works and makes for a really elegant solution.
这篇关于在单独的线程问题中初始化存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!