|Again, there are two parts to this.
On the server,
ExecuteScalarAsync returns a
Task, which uses an IO completion port behind the scenes to complete the task when the response has been received from the database. This allows the server to reuse the same thread-pool thread to service other requests whilst it waits for your database query to finish.
The client doesn't care what the server is doing. All it cares about is sending a request and receiving a response. But again, the network library can use an IO completion port behind the scenes so that your thread isn't tied up waiting for a response from the server. It doesn't matter to the client whether the server has implemented the API using
Tasks, or using a synchronous method; the network communication is the target for the asynchronous code.
I think at least part of the confusion here stems from the fact that you're using the same interface for the server implementation of the API and the client code to call that API. It's perfectly valid to have an
async method on the client calling a synchronous method on the server.
With Linq2Sql, it's not simple to make your server method
async *. But that doesn't mean the client can't be
protected override void Load()
_ = LoadAsync();
private async Task LoadAsync()
var customer = await AppCore.BizObject.GetCustomerByIdAsync(id);
} Again, take note of the fact that you should avoid
async void methods, and try to avoid spinning up a new
Task just to push work off the UI thread.
* You'd have to manually convert the query to a
SqlCommand and execute it by hand. Mike Taulty made a start on this back in 2007, before
await was around:
LINQ to SQL: Asynchronously Executing Queries | Mike Taulty[^]
Perhaps try something like this:
public async Task<CompanyEntity> GetCompanyByIdAsync(int companyId)
using (var dc = GetDataContext())
var query = (from c in dc.Companies
where c.Id == companyId
select new CompanyEntity
Id = c.Id,
CompanyName = c.CompanyName
using (var command = (SqlCommand)dc.GetCommand(query))
using (var reader = await command.ExecuteReaderAsync())
"These people looked deep within my soul and assigned me a number based on the order in which I joined."