Repository navigation
Conversation
|
Is there a particular goal for this set of changes other than making the code easier to work with? It's worth noting that while going to language based async makes the code a lot easier to work with it can have detrimental performance characteristics if you're capturing a lot of state. C#9 static lambdas would help with that if we could bump the langauge version. |
That certainly used to be true, and one must still be careful with what gets capture with async/await. However, nowadays async/await is generally optimized and can be considerably more efficient than more traditional callback-based approaches. I benchmarked async/await vs. ContinueWith a while ago and the former was considerably faster. It's always good to work with benchmarks when doing this kind of code change, but I'd say that any change from traditional callback-based async programming to async/await is in principle a positive direction :) |
I believe this could be the first step of changing Async pattern in the driver. Nothing could/would be changed drastically, without designing the core of the driver for async pattern, what we need is
I agree, but we cannot jump to C#9 while we are supporting netcore 3.1 and netfx 4.6. In near future, support for .NET 5 will be added to the driver and in my personal opinion that is where we will need all this changes to happen. |
| public partial class SqlBulkCopy | ||
| { | ||
| // Newly added member variables for Async modification, m = member variable to bcp. | ||
| private int _savedBatchSize = 0; // Save the batchsize so that changes are not affected unexpectedly. |
There was a problem hiding this comment.
Minor point. Initialization to default values for types other than span is generally unnecessary because of runtime guarantees. Doing so causes the code to be emitted in the ctor and while it isn't a big cost it isn't one that is needed either.
| Task reconnectTask; | ||
| try | ||
| { | ||
| reconnectTask = _connection.ValidateAndReconnect( |
There was a problem hiding this comment.
async capture, is it possible to pass the parserLock as a state parameter?
There was a problem hiding this comment.
I have not spend much time in reconnect task in SqlConnection. It follows the same steps, if the task returns null/task. I am not sure if AsyncHelper could be called to pass state on it. I will look into that tomorrow. In my opinion AsyncHelper is one the parts that we need to remove or at least simplify it with Task's built-in capabilities.
There was a problem hiding this comment.
Ideally AsyncHelper wouldn't be needed at all, i agree. Since it is currently needed and I've spent time around it this one stuck out to me while i was reviewing the code. If you'd prefer not to change this then I'm ok with that.
| _rowStateToSkip = DataRowState.Deleted; // Don't allow deleted rows | ||
| _rowSource = rows; | ||
| _dataTableSource = table; | ||
| _SqlDataReaderRowSource = null; | ||
| _rowSourceType = ValueSourceType.RowArray; | ||
| _rowEnumerator = rows.GetEnumerator(); | ||
| _isAsyncBulkCopy = true; | ||
| resultTask = WriteRowSourceToServerAsync(table.Columns.Count, cancellationToken); // It returns Task since _isAsyncBulkCopy = true; |
There was a problem hiding this comment.
This block and most of the method feels a bit boiler-plate. Do some checks, setup statistics, then do the variable bit and then cleanup. Is it worth abstracting it out as a separate method do you think?
There was a problem hiding this comment.
I agree. I will look into that tomorrow.
I really like the idea but have found that this can lead to multiple implementations all the way down and I'm not sure having two implementations of Run is good for maintenance. @roji probably has some good guidance here from the postgres driver, do you end up parallel or have a single implementation that both worlds use? and if so is it sync or async?
Yes I've seen that pattern. Parts of SqlCommand do the same and it's part of the cause of the string perf issues we've noted in the past. Essentially it tries fails and then tries again from the beginning. Easier on state management and simpler from an initial implementation perspective (because you always have full state to debug) but sort of sulky for perf. I have ideas on how to address it in a general way but I was trying to merge as much of the codebases from netfx and netcore before I started on major internal reworks. Run and all the methods above and below it in the parser should be changed to return OperationStatus instead of bool, with that done you can now identify the cause of a parse failure and possibly suspend state cleanly for a resumption on the next async packet.
Well... you sort of can. It's not a supported scenario but it is a working scenario. 😁 I checked with the langauge team on discord and as long we we don't use any language features that require library or runtime support it'll still work on downlevel frameworks. I understand your point though and the example of static lambdas to prevent accidental closure allocations is unlikely to be worth it, it would emit correct il working though. |
I don't know the internals at all, but doesn't SqlClient already have separate implementations for sync and async? If so, then at minimum, rewriting the callback-based async implementation to use async/await wouldn't be making the situation worse... More in detail... Npgsql does have a unified code path for sync and async for almost all the logic. This mean that you typically have a single method which accepts an Now, if all your methods have the async keyword on them, that means that for user sync APIs, you're potentially paying the overhead of the compiler-generated async state machine although it's not needed (since the method will never actually do any async operations. In fact, even for user async APIs, many calls won't necessarily need to do any I/O - the driver buffers internally, and so calls like DbDataReader.Read won't need to do any I/O (because the next row is already in memory). The overhead of async state machines has been greatly optimized in recent versions of .NET Core. However, for true pedal-to-the-metal perf, it's possible to provide a fast-path sync implementation which only calls into an async one when necessary: public ValueTask<SomeData> GetData(bool async, CancellationToken cancellationToken = default)
{
return dataAlreadyInMemory
? theData
: GetDataAsync();
async ValueTask<SomeData> GetDataAsync(bool async CancellationToken cancellationToken = default)
{
// Perform actual I/O and return the data
}
}With this kind of trick, you avoid going through state machines as long as data is already buffered; and if you have to do I/O, then the state machine overhead is likely negligible anyway. It's also sometimes worth merging two async methods into one, again to cut down on the number of async state machines you have in your stack - the overhead does add up. But I'd recommend not going into this kind of optimization right away - that can always happen later. My personal recommendation in terms of next steps would be something like:
Hope this helps... Am definitely available for any further questions/discussions on this.
You're right here - static lambdas (and some other C# 9 features) are compiler-only features which should always work. Other features (e.g. covariant return types) require the new runtime and therefore will not work. Static lambdas are generally a good idea to reduce allocations - I agree that SqlClient is probably facing more important perf problems, but it sure wouldn't hurt to use static lambdas when writing new code. |
|
There is some interesting code that handles sync and async callers in sync mode using api-async. An example of this is TdsParserStateObject.WriteBytes , it's fairly central to low level operations of writing bytes to the packets. Have a glance at the code. It's a fully sync method that signals whether it's working in async mode by returning a task to callers, if it returns a task that usually gets passed up the stack so whoever is doing the language async part gets to wait on it. The library itself does not await anything that I've ever seen it just sets up tasks and continuations. The problem I have with it is that because of all the looping and conditionals that exist here and levels above it it takes a lot of mental space to make sure your handle all routes through the code cleanly. I don't know if others have the same experience but I'd like to have some of the more important code in the library be significantly more straightforward to understand. There's a big Run method in the parser which is the main state machine implementation for incoming packets. State switches get long quickly and there are lots of quirks to account for because of old protocol versions and bug fixes. I'd prefer not to have two large state driver methods but having one which works in both sync and async modes either means a lot of conditionals on async or a completely separating io from parser driving and making all state transitions completely resumable which is complicated. |
|
@Wraith2 I very much agree with everything you say, and I'd say that the various async-related issues found in SqlClient are a good additional argument to try to make things saner by incrementally doing async/await (if possible). Callback-based async (like the WriteBytes method you linked to) is notoriously hard to follow and grasp, is inherently bug-prone, and those are the very reasons why async/await was invented - it allows writing and reasoning about async code in almost the same way as simple sync code. BTW the WriteBytes method you linked to is odd, in that it both returns a Task and accepts a TaskCompletionSource as a continuation (which, by the way means a lot of allocations as TCS cannot be recycled). I'd expect it to do either one or the either, but not both. |
| { | ||
| SqlStatistics.StopTimer(statistics); | ||
| } | ||
| await Task.WhenAll(resultTask); |
| private SqlInternalConnectionTds.SyncAsyncLock _parserLock = null; | ||
|
|
||
| /// <include file='../../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml' path='docs/members[@name="SqlBulkCopy"]/WriteToServerAsync[@name="DataRowParameter"]/*'/> | ||
| public async Task WriteToServerAsync(DataRow[] rows) => await WriteToServerAsync(rows, CancellationToken.None); |
There was a problem hiding this comment.
Why are we awaiting these methods?
There was a problem hiding this comment.
Unrelated comment: it is possible to remove the async and await keywords here, and just return the Task directly. This removes an async state machine and helps performance.
This trick can be done anywhere where the await call is the last line in a method.
Related Issue(s): Issue #716
This is a draft pull request and still has room to improve.
Current Design
Asyncandsynccalls inSqlBulkcopyare distinguished by two factors in Current design:By a boolean variable,
_isAsyncBulkCopy, which could be set totrueorfalsebased on the call from the user.For example, if user calls
WriteToServer(IDataReader reader), this will set the mentioned variable to false, sets the statistics and callsWriteRowSourceToServerAsync(reader.FieldCount, CancellationToken.None).When user calls
WriteToServerAsync(DbDataReader reader), this will call an overload of the same function withCancelation tokenadded to it and from there it calls the same function as sync call,WriteRowSourceToServerAsync.From here the only difference between
syncandasynccalls are based on return value of each task. If a return value of ataskis null, that implies thatsync patternis called and if it returns a ataskthat means anasynccall is in progress.Note
Same pattern has been used in different places of the M.D.S. For example reconnect task in
SqlConnectionfollows the same pattern.What has been done so far
SqlBulkCopyis separated to two partial classes,SqlBulkCopyandSqlBulkCopy.Async,in a new folder calledBulkCopy. I have been planning to do this for a long time and I found a good occasion. All SqlBulkCopy related is moved to this folder.Asyncfunctions are moved toSqlBulkcopy.Async_isAsyncBulkCopyis removed as it is not needed any more.Async/awaitpattern does not acceptout/reference/invalues. changed them accordingly.TaskCompletionSourceas much as possible inasync/awaitpattern, but not much luck. Needs more thinking and time. I may move back to this after GA.if/elsevalidation fortask result. The one validates if an actualtaskis returned (async) or it is null (sync).async/awaitpattern, which is not completed yet. (We probably need to redesignSqlBulkCopy.Async).