1

Can anyone tell me if there is any underlying difference between these 2 lines of code. I'm thinking there is or I would expect VS would suggest removing unneeded keywords. I don't understand what the difference is though and when is the proper time to use them. Both ways seem to work the same in my application but I'd like to be consistent and do what's best in this situation.

For this example I am getting a DataTable from the database to use as a data source for a drop down list. It's called from a synchronous UI function.

MyDropdown.DataSource = Task.Run(async () => await GetDataTableAsync(filter)).Result; MyDropdown.DataSource = Task.Run(() => GetDataTableAsync(filter)).Result; 

Thanks

5
  • 4
    you should bother more about the Task.Result-call, which will block your thread. Apart from this your two lines are identical. Commented Apr 16, 2024 at 15:19
  • 5
    "It's called from a synchronous UI function." - it shouldn't. I guess at some point in the call stack, there will be an event handler, right? That should be async void ... and then you can be async down the line without that kind of trouble. Commented Apr 16, 2024 at 15:36
  • Arguably neither are correct as mentioned. Commented Apr 16, 2024 at 15:59
  • Both are functionally and behaviorally the same. There is no observable difference between them. Out of curiosity, why did you avoid the simpler MyDropdown.DataSource = GetDataTableAsync(filter).Result;? Commented Apr 16, 2024 at 20:53
  • The only case that you'll see a difference in the behavior between the two, is if the GetDataTableAsync fails with multiple exceptions. In this rare case the async/await version will suppress all exceptions apart from the first. On the contrary the async/await-eliding version will propagate all exceptions. Commented Apr 16, 2024 at 20:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.