簡體   English   中英

異步后如何在主線程上運行代碼

[英]How to run code on the main thread after async

我的代碼只能在主線程上運行,但是在該代碼可以運行之前,我需要初始化一個對象。 無論如何,我可以強制異步代碼運行同步嗎? 等待之后的函數是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
        }
    }

您不能在構造函數中使用await,但可以將整個內容放入預訂WindowLoaded事件的異步事件處理程序中:

public MainWindow()
{
   this.Loaded += async (s, e) => 
   {
        await InitMbi(); 
        // mbi must be done at this point
        SomeCodeThatUsesMbi();
   };

   InitializeComponent();
}

並且不要忘記將InitMbi()的返回值更改為Task

public async Task InitMbi()
 // 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?
}

但是請注意,這將阻塞您的主線程!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM