When should you use Task.Run() rather than await?

后端 未结 2 1283
名媛妹妹
名媛妹妹 2021-01-23 13:12

I am storing the state of my data model. I clone the data model and then want to have it written to \"disk\" asynchronously.

Should I be using Task.Run() which runs it o

2条回答
  •  旧时难觅i
    2021-01-23 14:09

    You should use Task.Run for CPU-based work that you want to run on a thread pool thread.

    In your situation, you want to do I/O based work without blocking the UI, so Task.Run won't get you anything (unless you don't have asynchronous I/O APIs available).

    As a side note, you definitely do want to await this work. This makes error handling much cleaner.

    So, something like this should suffice:

    async void buttonSaveClick(..)
    {
      buttonSave.Enabled = false;
    
      try
      {
        await myModel.Clone().SaveAsync();
      }
      catch (Exception ex)
      {
        // Display error.
      }
    
      buttonSave.Enabled = true;
    }
    

提交回复
热议问题