gpt4 book ai didi

c# - 使用异步和等待

转载 作者:太空宇宙 更新时间:2023-11-03 10:47:55 27 4
gpt4 key购买 nike

    public async override void InitData()
{
_domainModel = new DomainModel()

ProgressIndicatorViewModel.Start();
_State = Getstate();
await _domainModel.Load(_State, ProgressIndicatorViewModel); //returns a task
ImageSelectionViewModel.UpdateState(_State); //returns void not a task!
ProgressIndicatorViewModel.Stop();

DispatcherHelper.UIDispatcher.Invoke(() => ImageSelectionViewModel.RefreshImages(_imageList));
}

我想让这两种方法(1.domaminModel.Load()、2.UpdateState())在同一个线程上一个接一个地运行。不在 UI 线程上。

我该怎么做?

最佳答案

i would like to make the two methods (1.domaminModel.Load(), 2. UpdateState()) to run on the same thread one after the other. not on the UI thread.

已更新,如果您只想要 _domainModel.LoadImageSelectionViewModel.UpdateState要在单独的非 UI 线程上运行,则只需执行以下操作:

public async override void InitData()
{
_domainModel = new DomainModel()

ProgressIndicatorViewModel.Start();
_State = Getstate();
await Task.Run(async () =>
{
await _domainModel.Load(_State, ProgressIndicatorViewModel))
ImageSelectionViewModel.UpdateState(_State); //returns void not a task!
});
ProgressIndicatorViewModel.Stop();

ImageSelectionViewModel.RefreshImages(_imageList);
}

注意你不需要需要DispatcherHelper.UIDispatcher.Invoke()然后包装。


如果你想要剩下的 InitData_domainModel.Load 之后在单独的线程上运行:

public async override void InitData()
{
_domainModel = new DomainModel()

ProgressIndicatorViewModel.Start();
_State = Getstate();
await Task.Run(() => _domainModel.Load(_State,
ProgressIndicatorViewModel)).ConfigureAwait(false);
ImageSelectionViewModel.UpdateState(_State); //returns void not a task!

DispatcherHelper.UIDispatcher.Invoke(() =>
{
ProgressIndicatorViewModel.Stop();
ImageSelectionViewModel.RefreshImages(_imageList)
});
}

请注意 Task.Run将自动为您解包嵌套任务(Task<Task<T>>)。此外,您可能需要移动 ProgressIndicatorViewModel.Stop()里面Dispatcher.Invoke .

取决于里面的内容_domainModel.Load , 你甚至可能不需要 Task.Run :

await _domainModel.Load(_State, 
ProgressIndicatorViewModel).ConfigureAwait(false);

附带说明一下,您可能应该在 async void InitData 中处理异常方法。你将无法在它之外处理它们。

关于c# - 使用异步和等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22731113/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com