异步后如何在主线程上运行代码

时间:2018-11-01 00:20:50

标签: c# wpf asynchronous

我有只在主线程上运行的代码,但是在该代码可以运行之前,我需要初始化一个对象。无论如何,我可以强制异步代码运行同步吗?等待之后的功能是API调用,因此我无法直接修改它们。

    public partial class MainWindow : Window
    {
        private MustBeInit mbi;

        public MainWindow() {
            InitializeComponent();
            // async code that initializes mbi
            InitMbi(); 
            // mbi must be done at this point
            SomeCodeThatUsesMbi();
        }

        public async void InitMbi() {
            mbi = new MustBeInit();
            await mbi.DoSomethingAsync();
            await mbi.DoSomethingElseAsync();

            // is there any way i can run these two methods as not await and
            // run them synchronous?
        }

        public void SomeCodeThatUsesMbi() {
            DoSomethingWithMbi(mbi); // mbi cannot be null here
        }
    }

2 个答案:

答案 0 :(得分:4)

您不能在构造函数中使用await,但是您可以将整个内容放入预订Loaded的{​​{1}}事件的异步事件处理程序中:

Window

不要忘记将public MainWindow() { this.Loaded += async (s, e) => { await InitMbi(); // mbi must be done at this point SomeCodeThatUsesMbi(); }; InitializeComponent(); } 的返回值更改为InitMbi()

Task

答案 1 :(得分:1)

// is there any way i can run these two methods as not await and
// run them synchronous?

是的,只需在方法调用之前删除await,例如:

public async void InitMbi() {
    mbi = new MustBeInit();
    mbi.DoSomethingAsync();
    mbi.DoSomethingElseAsync();

    // is there any way i can run these two methods as not await and
    // run them synchronous?
}

但是请注意,这将阻塞您的主线程!