diff --git a/src/Microsoft.OData.Core/Batch/ODataBatchOperationMessage.cs b/src/Microsoft.OData.Core/Batch/ODataBatchOperationMessage.cs
index a294029703..e310e9beef 100644
--- a/src/Microsoft.OData.Core/Batch/ODataBatchOperationMessage.cs
+++ b/src/Microsoft.OData.Core/Batch/ODataBatchOperationMessage.cs
@@ -137,16 +137,16 @@ public override Stream GetStream()
/// Asynchronously get the stream backing this message.
///
/// The stream for this message.
- public override Task GetStreamAsync()
+ public override ValueTask GetStreamAsync()
{
this.VerifyNotCompleted();
return GetStreamInnerAsync();
- async Task GetStreamInnerAsync()
+ async ValueTask GetStreamInnerAsync()
{
// notify the listener that the stream has been requested
- Task listenerTask = this.operationListener.StreamRequestedAsync();
+ ValueTask listenerTask = this.operationListener.StreamRequestedAsync();
// now remember that we are done processing the part header data (and only the payload is missing)
Stream contentStream = this.contentStreamCreatorFunc();
diff --git a/src/Microsoft.OData.Core/Batch/ODataBatchOperationRequestMessage.cs b/src/Microsoft.OData.Core/Batch/ODataBatchOperationRequestMessage.cs
index 0f35d93532..722812de2e 100644
--- a/src/Microsoft.OData.Core/Batch/ODataBatchOperationRequestMessage.cs
+++ b/src/Microsoft.OData.Core/Batch/ODataBatchOperationRequestMessage.cs
@@ -176,7 +176,7 @@ public Stream GetStream()
/// Asynchronously get the stream backing for this message.
/// The stream backing for this message.
- public Task GetStreamAsync()
+ public ValueTask GetStreamAsync()
{
return this.message.GetStreamAsync();
}
diff --git a/src/Microsoft.OData.Core/Batch/ODataBatchOperationResponseMessage.cs b/src/Microsoft.OData.Core/Batch/ODataBatchOperationResponseMessage.cs
index f78e1b2519..fabc211a5b 100644
--- a/src/Microsoft.OData.Core/Batch/ODataBatchOperationResponseMessage.cs
+++ b/src/Microsoft.OData.Core/Batch/ODataBatchOperationResponseMessage.cs
@@ -132,7 +132,7 @@ public Stream GetStream()
/// Asynchronously get the stream backing for this message.
/// The stream backing for this message.
- public Task GetStreamAsync()
+ public ValueTask GetStreamAsync()
{
return this.message.GetStreamAsync();
}
diff --git a/src/Microsoft.OData.Core/Batch/ODataBatchReader.cs b/src/Microsoft.OData.Core/Batch/ODataBatchReader.cs
index 1e2e72180d..c5248d1d6b 100644
--- a/src/Microsoft.OData.Core/Batch/ODataBatchReader.cs
+++ b/src/Microsoft.OData.Core/Batch/ODataBatchReader.cs
@@ -144,7 +144,7 @@ public bool Read()
/// Asynchronously reads the next part from the batch message payload.
/// A task that when completed indicates whether more items were read.
- public Task ReadAsync()
+ public ValueTask ReadAsync()
{
this.VerifyCanRead(false);
return this.InterceptExceptionAsync((thisParam) => thisParam.ReadAsynchronously());
@@ -164,7 +164,7 @@ public ODataBatchOperationRequestMessage CreateOperationRequestMessage()
/// Asynchronously returns an for reading the content of a batch operation.
/// A task that when completed returns a request message for reading the content of a batch operation.
- public async Task CreateOperationRequestMessageAsync()
+ public async ValueTask CreateOperationRequestMessageAsync()
{
this.VerifyCanCreateOperationRequestMessage(synchronousCall: false);
ODataBatchOperationRequestMessage result = await this.InterceptExceptionAsync(
@@ -188,7 +188,7 @@ public ODataBatchOperationResponseMessage CreateOperationResponseMessage()
/// Asynchronously returns an for reading the content of a batch operation.
/// A task that when completed returns a response message for reading the content of a batch operation.
- public async Task CreateOperationResponseMessageAsync()
+ public async ValueTask CreateOperationResponseMessageAsync()
{
this.VerifyCanCreateOperationResponseMessage(synchronousCall: false);
ODataBatchOperationResponseMessage result = await this.InterceptExceptionAsync(
@@ -214,10 +214,10 @@ void IODataStreamListener.StreamRequested()
/// A task representing any action that is running as part of the status change of the reader;
/// null if no such action exists.
///
- Task IODataStreamListener.StreamRequestedAsync()
+ ValueTask IODataStreamListener.StreamRequestedAsync()
{
this.operationState = OperationState.StreamRequested;
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -232,10 +232,10 @@ void IODataStreamListener.StreamDisposed()
/// This method is called asynchronously to notify that the content stream of a batch operation has been disposed.
///
/// A task that represents the asynchronous operation.
- Task IODataStreamListener.StreamDisposedAsync()
+ ValueTask IODataStreamListener.StreamDisposedAsync()
{
this.operationState = OperationState.StreamDisposed;
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -380,9 +380,9 @@ protected ODataBatchOperationResponseMessage BuildOperationResponseMessage(
/// The value of the TResult parameter contains an
/// that can be used to read the content of the batch request operation from.
///
- protected virtual Task CreateOperationRequestMessageImplementationAsync()
+ protected virtual ValueTask CreateOperationRequestMessageImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(this.CreateOperationRequestMessageImplementation);
+ return ValueTask.FromResult(this.CreateOperationRequestMessageImplementation());
}
///
@@ -394,9 +394,9 @@ protected virtual Task CreateOperationRequest
/// The value of the TResult parameter contains an
/// that can be used to read the content of the batch response operation from.
///
- protected virtual Task CreateOperationResponseMessageImplementationAsync()
+ protected virtual ValueTask CreateOperationResponseMessageImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(this.CreateOperationResponseMessageImplementation);
+ return ValueTask.FromResult(this.CreateOperationResponseMessageImplementation());
}
///
@@ -406,9 +406,9 @@ protected virtual Task CreateOperationRespon
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the batch reader state after the read.
///
- protected virtual Task ReadAtStartImplementationAsync()
+ protected virtual ValueTask ReadAtStartImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(this.ReadAtStartImplementation);
+ return ValueTask.FromResult(this.ReadAtStartImplementation());
}
///
@@ -418,9 +418,9 @@ protected virtual Task ReadAtStartImplementationAsync()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the batch reader state after the read.
///
- protected virtual Task ReadAtOperationImplementationAsync()
+ protected virtual ValueTask ReadAtOperationImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(this.ReadAtOperationImplementation);
+ return ValueTask.FromResult(this.ReadAtOperationImplementation());
}
///
@@ -430,9 +430,9 @@ protected virtual Task ReadAtOperationImplementationAsync
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the batch reader state after the read.
///
- protected virtual Task ReadAtChangesetStartImplementationAsync()
+ protected virtual ValueTask ReadAtChangesetStartImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(this.ReadAtChangesetStartImplementation);
+ return ValueTask.FromResult(this.ReadAtChangesetStartImplementation());
}
///
@@ -442,9 +442,9 @@ protected virtual Task ReadAtChangesetStartImplementation
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the batch reader state after the read.
///
- protected virtual Task ReadAtChangesetEndImplementationAsync()
+ protected virtual ValueTask ReadAtChangesetEndImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(this.ReadAtChangesetEndImplementation);
+ return ValueTask.FromResult(this.ReadAtChangesetEndImplementation());
}
///
@@ -495,7 +495,7 @@ private bool ReadSynchronously()
///
/// A task that when completed indicates whether more information was read.
[SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")]
- private Task ReadAsynchronously()
+ private ValueTask ReadAsynchronously()
{
return this.ReadImplementationAsync();
}
@@ -614,7 +614,7 @@ private bool ReadImplementation()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains true if more items were read; otherwise false.
///
- private async Task ReadImplementationAsync()
+ private async ValueTask ReadImplementationAsync()
{
Debug.Assert(this.ReaderOperationState != OperationState.StreamRequested, "Should have verified that no operation stream is still active.");
@@ -856,7 +856,7 @@ private T InterceptException(Func action)
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains the result of executing the .
///
- private async Task InterceptExceptionAsync(Func> action)
+ private async ValueTask InterceptExceptionAsync(Func> action)
{
try
{
diff --git a/src/Microsoft.OData.Core/Batch/ODataBatchWriter.cs b/src/Microsoft.OData.Core/Batch/ODataBatchWriter.cs
index 8cd6aa0b5a..33759f4d39 100644
--- a/src/Microsoft.OData.Core/Batch/ODataBatchWriter.cs
+++ b/src/Microsoft.OData.Core/Batch/ODataBatchWriter.cs
@@ -167,7 +167,7 @@ public void WriteStartBatch()
/// Asynchronously starts a new batch; can be only called once and as first call.
/// A task instance that represents the asynchronous write operation.
- public Task WriteStartBatchAsync()
+ public ValueTask WriteStartBatchAsync()
{
this.VerifyCanWriteStartBatch(false);
return this.WriteStartBatchImplementationAsync();
@@ -185,7 +185,7 @@ public void WriteEndBatch()
/// Asynchronously ends a batch; can only be called after WriteStartBatch has been called and if no other active change set or operation exist.
/// A task instance that represents the asynchronous write operation.
- public async Task WriteEndBatchAsync()
+ public async ValueTask WriteEndBatchAsync()
{
this.VerifyCanWriteEndBatch(false);
await this.WriteEndBatchImplementationAsync()
@@ -221,7 +221,7 @@ public void WriteStartChangeset(string changesetId)
/// Asynchronously starts a new change set without specifying group id;
/// This can only be called after WriteStartBatch and if no other active operation or change set exists.
/// A task instance that represents the asynchronous write operation.
- public Task WriteStartChangesetAsync()
+ public ValueTask WriteStartChangesetAsync()
{
return WriteStartChangesetAsync(Guid.NewGuid().ToString());
}
@@ -232,7 +232,7 @@ public Task WriteStartChangesetAsync()
/// The change set Id of the batch request. Cannot be null.
/// A task instance that represents the asynchronous write operation.
/// Thrown if the is null.
- public async Task WriteStartChangesetAsync(string changesetId)
+ public async ValueTask WriteStartChangesetAsync(string changesetId)
{
ExceptionUtils.CheckArgumentNotNull(changesetId, "changesetId");
@@ -252,7 +252,7 @@ public void WriteEndChangeset()
/// Asynchronously ends an active change set; this can only be called after WriteStartChangeset and only once for each change set.
/// A task instance that represents the asynchronous write operation.
- public async Task WriteEndChangesetAsync()
+ public async ValueTask WriteEndChangesetAsync()
{
this.VerifyCanWriteEndChangeset(false);
await this.WriteEndChangesetImplementationAsync()
@@ -308,7 +308,7 @@ public ODataBatchOperationRequestMessage CreateOperationRequestMessage(string me
///
/// The Content-ID value to write in ChangeSet header, would be ignored if is "GET".
/// A task that when completed returns the newly created operation request message.
- public Task CreateOperationRequestMessageAsync(string method, Uri uri, string contentId)
+ public ValueTask CreateOperationRequestMessageAsync(string method, Uri uri, string contentId)
{
return CreateOperationRequestMessageAsync(method, uri, contentId, BatchPayloadUriOption.AbsoluteUri);
}
@@ -322,7 +322,7 @@ public Task CreateOperationRequestMessageAsyn
///
/// The format of operation Request-URI, which could be AbsoluteUri, AbsoluteResourcePathAndHost, or RelativeResourcePath.
/// A task that when completed returns the newly created operation request message.
- public Task CreateOperationRequestMessageAsync(string method, Uri uri, string contentId,
+ public ValueTask CreateOperationRequestMessageAsync(string method, Uri uri, string contentId,
BatchPayloadUriOption payloadUriOption)
{
return CreateOperationRequestMessageAsync(method, uri, contentId, payloadUriOption, /*dependsOnIds*/null);
@@ -339,7 +339,7 @@ public Task CreateOperationRequestMessageAsyn
/// The format of operation Request-URI, which could be AbsoluteUri, AbsoluteResourcePathAndHost, or RelativeResourcePath.
/// The prerequisite request ids of this request.
/// A task that when completed returns the newly created operation request message.
- public Task CreateOperationRequestMessageAsync(
+ public ValueTask CreateOperationRequestMessageAsync(
string method,
Uri uri,
string contentId,
@@ -363,7 +363,7 @@ public ODataBatchOperationResponseMessage CreateOperationResponseMessage(string
/// Asynchronously creates an for writing an operation of a batch response.
/// The Content-ID value to write in ChangeSet head.
/// A task that when completed returns the newly created operation response message.
- public Task CreateOperationResponseMessageAsync(string contentId)
+ public ValueTask CreateOperationResponseMessageAsync(string contentId)
{
this.VerifyCanCreateOperationResponseMessage(false);
return this.CreateOperationResponseMessageImplementationAsync(contentId);
@@ -409,7 +409,7 @@ public Task FlushAsync()
/// A task representing any action that is running as part of the status change of the operation;
/// null if no such action exists.
///
- public abstract Task StreamRequestedAsync();
+ public abstract ValueTask StreamRequestedAsync();
///
/// This method is called to notify that the content stream of a batch operation has been disposed.
@@ -420,7 +420,7 @@ public Task FlushAsync()
/// This method is called asynchronously to notify that the content stream of a batch operation has been disposed.
///
/// A task that represents the asynchronous operation.
- public virtual Task StreamDisposedAsync()
+ public virtual ValueTask StreamDisposedAsync()
{
// NOTE: ODataBatchWriter class is abstract and public. This method body is intended
// to prevent a breaking change in subclasses that provide the implementation.
@@ -437,7 +437,7 @@ public virtual Task StreamDisposedAsync()
public abstract void OnInStreamError();
///
- public virtual Task OnInStreamErrorAsync()
+ public virtual ValueTask OnInStreamErrorAsync()
{
// NOTE: ODataBatchWriter class is abstract and public. This method body is intended
// to prevent a breaking change in subclasses that provide the implementation.
@@ -590,22 +590,20 @@ protected ODataBatchOperationResponseMessage BuildOperationResponseMessage(Strea
/// Asnchronously starts a new batch.
///
/// A task that represents the asynchronous write operation.
- protected virtual Task WriteStartBatchImplementationAsync()
+ protected virtual ValueTask WriteStartBatchImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(
- (thisParam) => thisParam.WriteStartBatchImplementation(),
- this);
+ this.WriteStartBatchImplementation();
+ return ValueTask.CompletedTask;
}
///
/// Asynchronously ends a batch.
///
/// A task that represents the asynchronous write operation.
- protected virtual Task WriteEndBatchImplementationAsync()
+ protected virtual ValueTask WriteEndBatchImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(
- (thisParam) => thisParam.WriteEndBatchImplementation(),
- this);
+ this.WriteEndBatchImplementation();
+ return ValueTask.CompletedTask;
}
///
@@ -613,23 +611,20 @@ protected virtual Task WriteEndBatchImplementationAsync()
///
/// The atomic group id, aka changeset GUID of the batch request.
/// A task that represents the asynchronous write operation.
- protected virtual Task WriteStartChangesetImplementationAsync(string groupOrChangesetId)
+ protected virtual ValueTask WriteStartChangesetImplementationAsync(string groupOrChangesetId)
{
- return TaskUtils.GetTaskForSynchronousOperation(
- (thisParam, groupOrChangesetIdParam) => thisParam.WriteStartChangesetImplementation(groupOrChangesetIdParam),
- this,
- groupOrChangesetId);
+ this.WriteStartChangesetImplementation(groupOrChangesetId);
+ return ValueTask.CompletedTask;
}
///
/// Asynchronously ends an active changeset.
///
/// A task that represents the asynchronous write operation.
- protected virtual Task WriteEndChangesetImplementationAsync()
+ protected virtual ValueTask WriteEndChangesetImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(
- (thisParam) => thisParam.WriteEndChangesetImplementation(),
- this);
+ this.WriteEndChangesetImplementation();
+ return ValueTask.CompletedTask;
}
///
@@ -644,15 +639,15 @@ protected virtual Task WriteEndChangesetImplementationAsync()
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains an
/// that can be used to write the request operation.
- protected virtual Task CreateOperationRequestMessageImplementationAsync(
+ protected virtual ValueTask CreateOperationRequestMessageImplementationAsync(
string method,
Uri uri,
string contentId,
BatchPayloadUriOption payloadUriOption,
IEnumerable dependsOnIds)
{
- return TaskUtils.GetTaskForSynchronousOperation(
- () => this.CreateOperationRequestMessageImplementation(
+ return ValueTask.FromResult(
+ this.CreateOperationRequestMessageImplementation(
method,
uri,
contentId,
@@ -667,10 +662,9 @@ protected virtual Task CreateOperationRequest
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains an
/// that can be used to write the response operation.
- protected virtual Task CreateOperationResponseMessageImplementationAsync(string contentId)
+ protected virtual ValueTask CreateOperationResponseMessageImplementationAsync(string contentId)
{
- return TaskUtils.GetTaskForSynchronousOperation(
- () => this.CreateOperationResponseMessageImplementation(contentId));
+ return ValueTask.FromResult(this.CreateOperationResponseMessageImplementation(contentId));
}
///
@@ -862,7 +856,7 @@ private ODataBatchOperationRequestMessage CreateOperationRequestMessageInternal(
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains an
/// that can be used to write the request operation.
- private async Task CreateOperationRequestMessageInternalAsync(
+ private async ValueTask CreateOperationRequestMessageInternalAsync(
string method,
Uri uri,
string contentId,
diff --git a/src/Microsoft.OData.Core/IODataOutputInStreamErrorListener.cs b/src/Microsoft.OData.Core/IODataOutputInStreamErrorListener.cs
index f47d4082ed..44822f92e9 100644
--- a/src/Microsoft.OData.Core/IODataOutputInStreamErrorListener.cs
+++ b/src/Microsoft.OData.Core/IODataOutputInStreamErrorListener.cs
@@ -32,6 +32,6 @@ internal interface IODataOutputInStreamErrorListener
/// If the listener returns, the writer should not allow any more writing, since the in-stream error is the last thing in the payload.
///
/// A task that represents the asynchronous operation.
- Task OnInStreamErrorAsync();
+ ValueTask OnInStreamErrorAsync();
}
}
diff --git a/src/Microsoft.OData.Core/IODataRequestMessageAsync.cs b/src/Microsoft.OData.Core/IODataRequestMessageAsync.cs
index 4f2afc1ea6..2b78994d4a 100644
--- a/src/Microsoft.OData.Core/IODataRequestMessageAsync.cs
+++ b/src/Microsoft.OData.Core/IODataRequestMessageAsync.cs
@@ -20,6 +20,6 @@ public interface IODataRequestMessageAsync : IODataRequestMessage
/// Asynchronously get the stream backing for this message.
/// The stream for this message.
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This is intentionally a method.")]
- Task GetStreamAsync();
+ ValueTask GetStreamAsync();
}
}
\ No newline at end of file
diff --git a/src/Microsoft.OData.Core/IODataResponseMessageAsync.cs b/src/Microsoft.OData.Core/IODataResponseMessageAsync.cs
index 576a49672b..22788f0b17 100644
--- a/src/Microsoft.OData.Core/IODataResponseMessageAsync.cs
+++ b/src/Microsoft.OData.Core/IODataResponseMessageAsync.cs
@@ -20,6 +20,6 @@ public interface IODataResponseMessageAsync : IODataResponseMessage
/// Asynchronously get the stream backing for this message.
/// The stream backing for this message.
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This is intentionally a method.")]
- Task GetStreamAsync();
+ ValueTask GetStreamAsync();
}
}
diff --git a/src/Microsoft.OData.Core/IODataStreamListener.cs b/src/Microsoft.OData.Core/IODataStreamListener.cs
index 4418a46362..9e85eba7b7 100644
--- a/src/Microsoft.OData.Core/IODataStreamListener.cs
+++ b/src/Microsoft.OData.Core/IODataStreamListener.cs
@@ -29,7 +29,7 @@ internal interface IODataStreamListener
/// A task representing any async operation that is running in reaction to the
/// status change (or null if no such action is required).
///
- Task StreamRequestedAsync();
+ ValueTask StreamRequestedAsync();
///
/// This method notifies the implementer of this interface that the content stream of a batch operation has been disposed.
@@ -40,6 +40,6 @@ internal interface IODataStreamListener
/// Asynchronously notifies the implementer of this interface that the content stream of an operation has been disposed.
///
/// A task that represents the asynchronous operation.
- Task StreamDisposedAsync();
+ ValueTask StreamDisposedAsync();
}
}
diff --git a/src/Microsoft.OData.Core/Json/BufferingJsonReader.cs b/src/Microsoft.OData.Core/Json/BufferingJsonReader.cs
index 8243e94807..04c05a6f36 100644
--- a/src/Microsoft.OData.Core/Json/BufferingJsonReader.cs
+++ b/src/Microsoft.OData.Core/Json/BufferingJsonReader.cs
@@ -247,7 +247,7 @@ public bool Read()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the node value of the last buffered read if buffering is on or off;
/// otherwise the node value of the last unbuffered read.
- public Task
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains true if a new node was found, or false if end of input was reached.
- public Task ReadAsync()
+ public ValueTask ReadAsync()
{
Debug.Assert(!this.parsingInStreamError, "!this.parsingInStreamError");
this.AssertAsynchronous();
@@ -285,7 +285,7 @@ public Task ReadAsync()
///
/// A task that represents the asynchronous operation.
/// true if the current value can be streamed; otherwise false.
- public virtual async Task CanStreamAsync()
+ public virtual async ValueTask CanStreamAsync()
{
this.AssertAsynchronous();
@@ -306,7 +306,7 @@ public virtual async Task CanStreamAsync()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains a used to read a stream value.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1825:Avoid zero-length array allocations.", Justification = "")]
- public virtual async Task CreateReadStreamAsync()
+ public virtual async ValueTask CreateReadStreamAsync()
{
this.AssertAsynchronous();
@@ -341,7 +341,7 @@ await this.innerReader.ReadAsync()
///
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains a for reading the text value.
- public virtual async Task CreateTextReaderAsync()
+ public virtual async ValueTask CreateTextReaderAsync()
{
this.AssertAsynchronous();
@@ -482,7 +482,7 @@ internal bool StartBufferingAndTryToReadInStreamErrorPropertyValue(out ODataErro
/// Asynchronously puts the reader into the state where it buffers read nodes.
///
/// A task that represents the asynchronous operation.
- internal async Task StartBufferingAsync()
+ internal async ValueTask StartBufferingAsync()
{
Debug.Assert(!this.isBuffering, "Buffering is already turned on. Must not call StartBuffering again.");
this.AssertAsynchronous();
@@ -520,7 +520,7 @@ internal async Task StartBufferingAsync()
/// The value of the TResult parameter contains a tuple comprising of:
/// 1). A value of true if the current value is an in-stream error value; otherwise false.
/// 2). An instance that was read from the payload.
- internal async Task> StartBufferingAndTryToReadInStreamErrorPropertyValueAsync()
+ internal async ValueTask> StartBufferingAndTryToReadInStreamErrorPropertyValueAsync()
{
this.AssertNotBuffering();
this.AssertAsynchronous();
@@ -681,7 +681,7 @@ protected virtual void ProcessObjectValue()
/// represents an in-stream error. If so, it throws an . If false, this check will not happen.
/// This parsingInStremError field is set to true when trying to parse an in-stream error; in normal operation it is false.
///
- protected async Task ReadInternalAsync()
+ protected async ValueTask ReadInternalAsync()
{
this.AssertAsynchronous();
@@ -754,7 +754,7 @@ await this.innerReader.ReadAsync().ConfigureAwait(false) :
/// once it returns the reader will be returned to the position before the method was called.
/// The reader is always positioned on a start object when this method is called.
///
- protected virtual async Task ProcessObjectValueAsync()
+ protected virtual async ValueTask ProcessObjectValueAsync()
{
Debug.Assert(this.currentBufferedNode.NodeType == JsonNodeType.StartObject, "this.currentBufferedNode.NodeType == JsonNodeType.StartObject");
Debug.Assert(this.parsingInStreamError, "this.parsingInStreamError");
diff --git a/src/Microsoft.OData.Core/Json/IJsonReader.cs b/src/Microsoft.OData.Core/Json/IJsonReader.cs
index cee3136a1f..4553f0cf17 100644
--- a/src/Microsoft.OData.Core/Json/IJsonReader.cs
+++ b/src/Microsoft.OData.Core/Json/IJsonReader.cs
@@ -68,7 +68,7 @@ public interface IJsonReader
///
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains true if a new node was found, or false if end of input was reached.
- Task ReadAsync();
+ ValueTask ReadAsync();
///
/// Asynchronously returns the value of the last reported node.
@@ -85,27 +85,27 @@ public interface IJsonReader
/// - Double if a number which doesn't fit into Int32 was found.
/// If the last node is a Property this property returns a string which is the name of the property.
///
- Task GetValueAsync();
+ ValueTask GetValueAsync();
///
/// Asynchronously creates a Stream for reading a binary value.
///
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains a for reading the binary value.
- Task CreateReadStreamAsync();
+ ValueTask CreateReadStreamAsync();
///
/// Asynchronously creates a TextReader for reading a string value.
///
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains a for reading the string value.
- Task CreateTextReaderAsync();
+ ValueTask CreateTextReaderAsync();
///
/// Asynchronously checks whether or not the current value can be streamed.
///
/// A task that represents the asynchronous operation.
/// true if the current value can be streamed; otherwise false.
- Task CanStreamAsync();
+ ValueTask CanStreamAsync();
}
}
diff --git a/src/Microsoft.OData.Core/Json/IJsonWriter.cs b/src/Microsoft.OData.Core/Json/IJsonWriter.cs
index fd4b3f0d92..5eb2c4636b 100644
--- a/src/Microsoft.OData.Core/Json/IJsonWriter.cs
+++ b/src/Microsoft.OData.Core/Json/IJsonWriter.cs
@@ -213,45 +213,45 @@ public interface IJsonWriter
///
/// A task that represents the asynchronous operation.
[Obsolete("This will be dropped in the 9.x release.")]
- Task StartPaddingFunctionScopeAsync();
+ ValueTask StartPaddingFunctionScopeAsync();
///
/// Asynchronously ends the padding function scope.
///
/// A task that represents the asynchronous operation.
[Obsolete("This will be dropped in the 9.x release.")]
- Task EndPaddingFunctionScopeAsync();
+ ValueTask EndPaddingFunctionScopeAsync();
///
/// Asynchronously starts the object scope.
///
/// A task that represents the asynchronous operation.
- Task StartObjectScopeAsync();
+ ValueTask StartObjectScopeAsync();
///
/// Asynchronously ends the current object scope.
///
/// A task that represents the asynchronous operation.
- Task EndObjectScopeAsync();
+ ValueTask EndObjectScopeAsync();
///
/// Asynchronously starts the array scope.
///
/// A task that represents the asynchronous operation.
- Task StartArrayScopeAsync();
+ ValueTask StartArrayScopeAsync();
///
/// Asynchronously ends the current array scope.
///
/// A task that represents the asynchronous operation.
- Task EndArrayScopeAsync();
+ ValueTask EndArrayScopeAsync();
///
/// Asynchronously writes the name for the object property.
///
/// Name of the object property.
/// A task that represents the asynchronous write operation.
- Task WriteNameAsync(string name);
+ ValueTask WriteNameAsync(string name);
///
/// Asynchronously writes a function name for JSON padding.
@@ -259,119 +259,119 @@ public interface IJsonWriter
/// Name of the padding function to write.
/// A task that represents the asynchronous write operation.
[Obsolete("This will be dropped in the 9.x release.")]
- Task WritePaddingFunctionNameAsync(string functionName);
+ ValueTask WritePaddingFunctionNameAsync(string functionName);
///
/// Asynchronously writes a boolean value.
///
/// Boolean value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(bool value);
+ ValueTask WriteValueAsync(bool value);
///
/// Asynchronously writes an integer value.
///
/// Integer value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(int value);
+ ValueTask WriteValueAsync(int value);
///
/// Asynchronously writes a float value.
///
/// Float value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(float value);
+ ValueTask WriteValueAsync(float value);
///
/// Asynchronously writes a short value.
///
/// Short value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(short value);
+ ValueTask WriteValueAsync(short value);
///
/// Asynchronously writes a long value.
///
/// Long value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(long value);
+ ValueTask WriteValueAsync(long value);
///
/// Asynchronously writes a double value.
///
/// Double value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(double value);
+ ValueTask WriteValueAsync(double value);
///
/// Asynchronously writes a Guid value.
///
/// Guid value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(Guid value);
+ ValueTask WriteValueAsync(Guid value);
///
/// Asynchronously writes a decimal value
///
/// Decimal value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(decimal value);
+ ValueTask WriteValueAsync(decimal value);
///
/// Asynchronously writes a DateTimeOffset value
///
/// DateTimeOffset value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(DateTimeOffset value);
+ ValueTask WriteValueAsync(DateTimeOffset value);
///
/// Asynchronously writes a TimeSpan value
///
/// TimeSpan value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(TimeSpan value);
+ ValueTask WriteValueAsync(TimeSpan value);
///
/// Asynchronously writes a byte value.
///
/// Byte value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(byte value);
+ ValueTask WriteValueAsync(byte value);
///
/// Asynchronously writes an sbyte value.
///
/// SByte value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(sbyte value);
+ ValueTask WriteValueAsync(sbyte value);
///
/// Asynchronously writes a string value.
///
/// String value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(string value);
+ ValueTask WriteValueAsync(string value);
///
/// Asynchronously writes a byte array.
///
/// Byte array to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(byte[] value);
+ ValueTask WriteValueAsync(byte[] value);
///
/// Asynchronously writes a Date value
///
/// Date value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(Date value);
+ ValueTask WriteValueAsync(Date value);
///
/// Asynchronously writes a TimeOfDay value
///
/// TimeOfDay value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(TimeOfDay value);
+ ValueTask WriteValueAsync(TimeOfDay value);
#if NETCOREAPP
@@ -380,7 +380,7 @@ public interface IJsonWriter
///
/// The value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteValueAsync(JsonElement value);
+ ValueTask WriteValueAsync(JsonElement value);
#endif
///
@@ -388,7 +388,7 @@ public interface IJsonWriter
///
/// Raw value to be written.
/// A task that represents the asynchronous write operation.
- Task WriteRawValueAsync(string rawValue);
+ ValueTask WriteRawValueAsync(string rawValue);
///
/// Asynchronously clears all buffers for the current writer.
@@ -401,7 +401,7 @@ public interface IJsonWriter
///
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains the stream to write the property value to.
- Task StartStreamValueScopeAsync();
+ ValueTask StartStreamValueScopeAsync();
///
/// Asynchronously starts the TextWriter value scope.
@@ -409,18 +409,18 @@ public interface IJsonWriter
/// ContentType of the string being written.
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains the textwriter to write the text property value to.
- Task StartTextWriterValueScopeAsync(string contentType);
+ ValueTask StartTextWriterValueScopeAsync(string contentType);
///
/// Asynchronously ends the current stream property value scope.
///
/// A task that represents the asynchronous operation.
- Task EndStreamValueScopeAsync();
+ ValueTask EndStreamValueScopeAsync();
///
/// Asynchronously ends the TextWriter value scope.
///
/// A task that represents the asynchronous operation.
- Task EndTextWriterValueScopeAsync();
+ ValueTask EndTextWriterValueScopeAsync();
}
}
diff --git a/src/Microsoft.OData.Core/Json/JsonInstanceAnnotationWriter.cs b/src/Microsoft.OData.Core/Json/JsonInstanceAnnotationWriter.cs
index 44661357bf..edfe6a0439 100644
--- a/src/Microsoft.OData.Core/Json/JsonInstanceAnnotationWriter.cs
+++ b/src/Microsoft.OData.Core/Json/JsonInstanceAnnotationWriter.cs
@@ -253,7 +253,7 @@ internal void WriteInstanceAnnotation(
/// Whether to ignore the filter in settings.
/// The name of the property this instance annotation applies to
/// A task that represents the asynchronous write operation.
- internal Task WriteInstanceAnnotationsAsync(
+ internal ValueTask WriteInstanceAnnotationsAsync(
ICollection instanceAnnotations,
InstanceAnnotationWriteTracker tracker,
bool ignoreFilter = false,
@@ -266,7 +266,7 @@ internal Task WriteInstanceAnnotationsAsync(
if (instanceAnnotations.Count == 0)
{
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
HashSet instanceAnnotationNames = new HashSet(StringComparer.Ordinal);
@@ -278,7 +278,7 @@ internal Task WriteInstanceAnnotationsAsync(
{
return WriteInstanceAnnotationsListAsync(instanceAnnotationsList, tracker, instanceAnnotationNames, ignoreFilter, propertyName);
- async Task WriteInstanceAnnotationsListAsync(
+ async ValueTask WriteInstanceAnnotationsListAsync(
List innerInstanceAnnotationsList,
InstanceAnnotationWriteTracker innerInstanceAnnotationWriteTracker,
HashSet innerInstanceAnnotationNames,
@@ -300,7 +300,7 @@ await this.WriteAndTrackInstanceAnnotationAsync(
{
return WriteInstanceAnnotationsInnerAsync(instanceAnnotations, tracker, instanceAnnotationNames, ignoreFilter, propertyName);
- async Task WriteInstanceAnnotationsInnerAsync(
+ async ValueTask WriteInstanceAnnotationsInnerAsync(
ICollection innerInstanceAnnotations,
InstanceAnnotationWriteTracker innerInstanceAnnotationWriteTracker,
HashSet innerInstanceAnnotationNames,
@@ -327,7 +327,7 @@ await this.WriteAndTrackInstanceAnnotationAsync(
/// Collection of instance annotations to write.
/// The name of the property this instance annotation applies to
/// If writing an undeclared property.
- internal Task WriteInstanceAnnotationsAsync(
+ internal ValueTask WriteInstanceAnnotationsAsync(
ICollection instanceAnnotations,
string propertyName = null,
bool isUndeclaredProperty = false)
@@ -348,7 +348,7 @@ internal Task WriteInstanceAnnotationsAsync(
/// Asynchronously writes all the instance annotations specified in of error.
///
/// Collection of instance annotations to write.
- internal Task WriteInstanceAnnotationsForErrorAsync(ICollection instanceAnnotations)
+ internal ValueTask WriteInstanceAnnotationsForErrorAsync(ICollection instanceAnnotations)
{
Debug.Assert(instanceAnnotations != null, "instanceAnnotations should not be null if we called this");
return this.WriteInstanceAnnotationsAsync(instanceAnnotations, new InstanceAnnotationWriteTracker(), true);
@@ -360,7 +360,7 @@ internal Task WriteInstanceAnnotationsForErrorAsync(ICollectionThe instance annotation to write.
/// Whether to ignore the filter in settings.
/// The name of the property this instance annotation applies tos
- internal async Task WriteInstanceAnnotationAsync(
+ internal async ValueTask WriteInstanceAnnotationAsync(
ODataInstanceAnnotation instanceAnnotation,
bool ignoreFilter = false,
string propertyName = null)
@@ -569,7 +569,7 @@ await this.WriteInstanceAnnotationAsync(annotation, ignoreFilter, propertyName)
/// The collection of instance annotations
/// The name of the property the instance annotations apply to
/// A task that represents the asynchronous write operation.
- private async Task WriteInstanceAnnotationsForUndeclaredPropertyAsync(ICollection instanceAnnotations, string propertyName)
+ private async ValueTask WriteInstanceAnnotationsForUndeclaredPropertyAsync(ICollection instanceAnnotations, string propertyName)
{
// write undeclared property's all annotations
// optimize the foreach when instanceAnnotations is a List to avoid enumerator allocations on the heap
@@ -613,7 +613,7 @@ private void WriteInstanceAnnotationName(string propertyName, string annotationN
///
/// The name of the property this instance annotation applied to.
/// The name of the instance annotation.
- private Task WriteInstanceAnnotationNameAsync(string propertyName, string annotationName)
+ private ValueTask WriteInstanceAnnotationNameAsync(string propertyName, string annotationName)
{
if (propertyName != null)
{
diff --git a/src/Microsoft.OData.Core/Json/JsonODataAnnotationWriter.cs b/src/Microsoft.OData.Core/Json/JsonODataAnnotationWriter.cs
index 3f3bd4efe7..df7a24b539 100644
--- a/src/Microsoft.OData.Core/Json/JsonODataAnnotationWriter.cs
+++ b/src/Microsoft.OData.Core/Json/JsonODataAnnotationWriter.cs
@@ -127,7 +127,7 @@ public void WriteInstanceAnnotationName(string annotationName)
/// The type name to write.
/// Whether to write the raw typeName without removing/adding prefix 'Edm.'/'#'.
/// A task that represents the asynchronous write operation.
- public async Task WriteODataTypeInstanceAnnotationAsync(string typeName, bool writeRawValue = false)
+ public async ValueTask WriteODataTypeInstanceAnnotationAsync(string typeName, bool writeRawValue = false)
{
Debug.Assert(this.jsonWriter != null, "this.jsonWriter != null");
Debug.Assert(typeName != null, "typeName != null");
@@ -153,7 +153,7 @@ await this.jsonWriter.WriteValueAsync(WriterUtils.PrefixTypeNameForWriting(typeN
/// The name of the property for which to write the odata.type annotation.
/// The type name to write.
/// A task that represents the asynchronous write operation.
- public async Task WriteODataTypePropertyAnnotationAsync(string propertyName, string typeName)
+ public async ValueTask WriteODataTypePropertyAnnotationAsync(string propertyName, string typeName)
{
Debug.Assert(this.jsonWriter != null, "this.jsonWriter != null");
Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)");
@@ -172,7 +172,7 @@ await this.jsonWriter.WriteValueAsync(WriterUtils.PrefixTypeNameForWriting(typeN
/// The name of the property to annotate.
/// The name of the annotation to write.
/// A task that represents the asynchronous write operation.
- public Task WritePropertyAnnotationNameAsync(string propertyName, string annotationName)
+ public ValueTask WritePropertyAnnotationNameAsync(string propertyName, string annotationName)
{
Debug.Assert(this.jsonWriter != null, "this.jsonWriter != null");
Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)");
@@ -188,7 +188,7 @@ public Task WritePropertyAnnotationNameAsync(string propertyName, string annotat
///
/// The name of the instance annotation to write.
/// A task that represents the asynchronous write operation.
- public Task WriteInstanceAnnotationNameAsync(string annotationName)
+ public ValueTask WriteInstanceAnnotationNameAsync(string annotationName)
{
Debug.Assert(this.jsonWriter != null, "this.jsonWriter != null");
Debug.Assert(!string.IsNullOrEmpty(annotationName), "!string.IsNullOrEmpty(annotationName)");
diff --git a/src/Microsoft.OData.Core/Json/JsonReader.cs b/src/Microsoft.OData.Core/Json/JsonReader.cs
index fc64b6bf23..12a28c9d3d 100644
--- a/src/Microsoft.OData.Core/Json/JsonReader.cs
+++ b/src/Microsoft.OData.Core/Json/JsonReader.cs
@@ -521,7 +521,7 @@ public TextReader CreateTextReader()
/// - Double if a number which doesn't fit into Int32 was found.
/// If the last node is a Property this property returns a string which is the name of the property.
///
- public virtual async Task GetValueAsync()
+ public virtual async ValueTask GetValueAsync()
{
if (this.readingStream)
{
@@ -559,16 +559,9 @@ public virtual async Task GetValueAsync()
///
/// A task that represents the asynchronous operation.
/// true if the current value can be streamed; otherwise false.
- public Task CanStreamAsync()
+ public ValueTask CanStreamAsync()
{
- if (this.canStream)
- {
- return Task.FromResult(true);
- }
- else
- {
- return Task.FromResult(false);
- }
+ return ValueTask.FromResult(this.canStream);
}
///
@@ -578,7 +571,7 @@ public Task CanStreamAsync()
/// The value of the TResult parameter contains true if a new node was found,
/// or false if end of input was reached.
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Not really feasible to extract code to methods without introducing unnecessary complexity.")]
- public virtual async Task ReadAsync()
+ public virtual async ValueTask ReadAsync()
{
if (this.readingStream)
{
@@ -755,7 +748,7 @@ public virtual async Task ReadAsync()
///
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains a for reading a base64 URL encoded binary value.
- public async Task CreateReadStreamAsync()
+ public async ValueTask CreateReadStreamAsync()
{
if (!this.canStream)
{
@@ -770,7 +763,7 @@ await this.ParseNullPrimitiveValueAsync()
this.scopes.Peek().ValueCount++;
await this.ReadAsync()
.ConfigureAwait(false);
- return new ODataBinaryStreamReader((a, b, c) => { return Task.FromResult(0); });
+ return new ODataBinaryStreamReader((a, b, c) => { return ValueTask.FromResult(0); });
}
this.tokenStartIndex++;
@@ -783,7 +776,7 @@ await this.ReadAsync()
///
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains a for reading a text value.
- public async Task CreateTextReaderAsync()
+ public async ValueTask CreateTextReaderAsync()
{
if (!this.canStream)
{
@@ -802,7 +795,7 @@ await this.ParseNullPrimitiveValueAsync()
this.scopes.Peek().ValueCount++;
await this.ReadAsync()
.ConfigureAwait(false);
- return new ODataTextStreamReader((a, b, c) => { return Task.FromResult(0); });
+ return new ODataTextStreamReader((a, b, c) => { return ValueTask.FromResult(0); });
}
// skip over the opening quote character for a string value
@@ -2028,7 +2021,7 @@ private async Task ParseNameAsync()
/// Note that the string parsing can never end with EndOfInput, since we're already seen the quote.
/// So it can either return a string successfully or fail.
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Splitting the function would make it hard to understand.")]
- private async Task ReadCharsAsync(char[] chars, int offset, int maxLength)
+ private async ValueTask ReadCharsAsync(char[] chars, int offset, int maxLength)
{
if (!readingStream)
{
diff --git a/src/Microsoft.OData.Core/Json/JsonWriter.Async.cs b/src/Microsoft.OData.Core/Json/JsonWriter.Async.cs
index ea4fba3875..f5dd9382f8 100644
--- a/src/Microsoft.OData.Core/Json/JsonWriter.Async.cs
+++ b/src/Microsoft.OData.Core/Json/JsonWriter.Async.cs
@@ -22,14 +22,14 @@ namespace Microsoft.OData.Json
internal sealed partial class JsonWriter
{
///
- public Task StartPaddingFunctionScopeAsync()
+ public ValueTask StartPaddingFunctionScopeAsync()
{
Debug.Assert(this.scopes.Count == 0, "Padding scope can only be the outer most scope.");
return this.StartScopeAsync(ScopeType.Padding);
}
///
- public async Task EndPaddingFunctionScopeAsync()
+ public async ValueTask EndPaddingFunctionScopeAsync()
{
Debug.Assert(this.scopes.Count > 0, "No scope to end.");
@@ -43,13 +43,13 @@ public async Task EndPaddingFunctionScopeAsync()
}
///
- public Task StartObjectScopeAsync()
+ public ValueTask StartObjectScopeAsync()
{
return this.StartScopeAsync(ScopeType.Object);
}
///
- public async Task EndObjectScopeAsync()
+ public async ValueTask EndObjectScopeAsync()
{
Debug.Assert(this.scopes.Count > 0, "No scope to end.");
@@ -63,13 +63,13 @@ public async Task EndObjectScopeAsync()
}
///
- public Task StartArrayScopeAsync()
+ public ValueTask StartArrayScopeAsync()
{
return this.StartScopeAsync(ScopeType.Array);
}
///
- public async Task EndArrayScopeAsync()
+ public async ValueTask EndArrayScopeAsync()
{
Debug.Assert(this.scopes.Count > 0, "No scope to end.");
@@ -83,7 +83,7 @@ public async Task EndArrayScopeAsync()
}
///
- public async Task WriteNameAsync(string name)
+ public async ValueTask WriteNameAsync(string name)
{
Debug.Assert(!string.IsNullOrEmpty(name), "The name must be specified.");
Debug.Assert(this.scopes.Count > 0, "There must be an active scope for name to be written.");
@@ -103,41 +103,41 @@ await this.writer.WriteEscapedJsonStringAsync(name, this.stringEscapeOption, thi
}
///
- public Task WritePaddingFunctionNameAsync(string functionName)
+ public async ValueTask WritePaddingFunctionNameAsync(string functionName)
{
- return this.writer.WriteAsync(functionName);
+ await this.writer.WriteAsync(functionName);
}
///
- public async Task WriteValueAsync(bool value)
+ public async ValueTask WriteValueAsync(bool value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(int value)
+ public async ValueTask WriteValueAsync(int value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(float value)
+ public async ValueTask WriteValueAsync(float value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(short value)
+ public async ValueTask WriteValueAsync(short value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(long value)
+ public async ValueTask WriteValueAsync(long value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
@@ -154,21 +154,21 @@ await this.writer.WriteValueAsync(value.ToString(CultureInfo.InvariantCulture),
}
///
- public async Task WriteValueAsync(double value)
+ public async ValueTask WriteValueAsync(double value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(Guid value)
+ public async ValueTask WriteValueAsync(Guid value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(decimal value)
+ public async ValueTask WriteValueAsync(decimal value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
@@ -185,7 +185,7 @@ await this.writer.WriteValueAsync(value.ToString(CultureInfo.InvariantCulture),
}
///
- public async Task WriteValueAsync(DateTimeOffset value)
+ public async ValueTask WriteValueAsync(DateTimeOffset value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value, ODataJsonDateTimeFormat.ISO8601DateTime)
@@ -193,42 +193,42 @@ await this.writer.WriteValueAsync(value, ODataJsonDateTimeFormat.ISO8601DateTime
}
///
- public async Task WriteValueAsync(TimeSpan value)
+ public async ValueTask WriteValueAsync(TimeSpan value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(TimeOfDay value)
+ public async ValueTask WriteValueAsync(TimeOfDay value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(Date value)
+ public async ValueTask WriteValueAsync(Date value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(byte value)
+ public async ValueTask WriteValueAsync(byte value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(sbyte value)
+ public async ValueTask WriteValueAsync(sbyte value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value).ConfigureAwait(false);
}
///
- public async Task WriteValueAsync(string value)
+ public async ValueTask WriteValueAsync(string value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value, this.stringEscapeOption, this.wrappedBuffer, this.ArrayPool)
@@ -236,14 +236,14 @@ await this.writer.WriteValueAsync(value, this.stringEscapeOption, this.wrappedBu
}
///
- public async Task WriteValueAsync(byte[] value)
+ public async ValueTask WriteValueAsync(byte[] value)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteValueAsync(value, this.wrappedBuffer, this.ArrayPool).ConfigureAwait(false);
}
#if NETCOREAPP
- public Task WriteValueAsync(JsonElement value)
+ public ValueTask WriteValueAsync(JsonElement value)
{
switch (value.ValueKind)
{
@@ -265,11 +265,11 @@ public Task WriteValueAsync(JsonElement value)
// we've exhausted all known JSON types, if we get
// to this point, then it's undefined behavior
Debug.Fail($"Unexpected JSON ValueKind {value.ValueKind}");
- return Task.CompletedTask;
+ return ValueTask.CompletedTask;
}
}
- private async Task WriteJsonElementArrayAsync(JsonElement value)
+ private async ValueTask WriteJsonElementArrayAsync(JsonElement value)
{
Debug.Assert(value.ValueKind == JsonValueKind.Array);
@@ -282,7 +282,7 @@ private async Task WriteJsonElementArrayAsync(JsonElement value)
await this.EndArrayScopeAsync().ConfigureAwait(false);
}
- private async Task WriteJsonElementObjectAsync(JsonElement value)
+ private async ValueTask WriteJsonElementObjectAsync(JsonElement value)
{
Debug.Assert(value.ValueKind == JsonValueKind.Object);
@@ -296,7 +296,7 @@ private async Task WriteJsonElementObjectAsync(JsonElement value)
await this.EndObjectScopeAsync().ConfigureAwait(false);
}
- private Task WriteJsonElementNumberAsync(JsonElement value)
+ private ValueTask WriteJsonElementNumberAsync(JsonElement value)
{
Debug.Assert(value.ValueKind == JsonValueKind.Number);
@@ -356,12 +356,12 @@ private Task WriteJsonElementNumberAsync(JsonElement value)
}
Debug.Fail($"Exhausted all known JSON number types and did not find match.");
- return Task.CompletedTask;
+ return ValueTask.CompletedTask;
}
#endif
///
- public async Task WriteRawValueAsync(string rawValue)
+ public async ValueTask WriteRawValueAsync(string rawValue)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteAsync(rawValue).ConfigureAwait(false);
@@ -398,7 +398,7 @@ public async ValueTask DisposeAsync()
#endif
///
- public async Task StartStreamValueScopeAsync()
+ public async ValueTask StartStreamValueScopeAsync()
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
await this.writer.WriteAsync(JsonConstants.QuoteCharacter).ConfigureAwait(false);
@@ -414,7 +414,7 @@ public async Task StartStreamValueScopeAsync()
}
///
- public async Task EndStreamValueScopeAsync()
+ public async ValueTask EndStreamValueScopeAsync()
{
await this.binaryValueStream.FlushAsync().ConfigureAwait(false);
#if NETCOREAPP
@@ -428,7 +428,7 @@ public async Task EndStreamValueScopeAsync()
}
///
- public async Task StartTextWriterValueScopeAsync(string contentType)
+ public async ValueTask StartTextWriterValueScopeAsync(string contentType)
{
await this.WriteValueSeparatorAsync().ConfigureAwait(false);
this.currentContentType = contentType;
@@ -446,14 +446,19 @@ await this.writer.WriteAsync(JsonConstants.QuoteCharacter)
}
///
- public Task EndTextWriterValueScopeAsync()
+ public ValueTask EndTextWriterValueScopeAsync()
{
if (!IsWritingJson)
{
- return this.writer.WriteAsync(JsonConstants.QuoteCharacter);
+ return WriteQuoteAsync();
}
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
+
+ async ValueTask WriteQuoteAsync()
+ {
+ await this.writer.WriteAsync(JsonConstants.QuoteCharacter).ConfigureAwait(false);
+ }
}
///
@@ -485,7 +490,7 @@ private Task WriteValueSeparatorAsync()
///
/// The scope type to start.
/// A task that represents the asynchronous write operation.
- private async Task StartScopeAsync(ScopeType type)
+ private async ValueTask StartScopeAsync(ScopeType type)
{
if (this.scopes.Count != 0 && this.scopes.Peek().Type != ScopeType.Padding)
{
diff --git a/src/Microsoft.OData.Core/Json/JsonWriterExtensions.Async.cs b/src/Microsoft.OData.Core/Json/JsonWriterExtensions.Async.cs
index a492ddfcd3..243cca8670 100644
--- a/src/Microsoft.OData.Core/Json/JsonWriterExtensions.Async.cs
+++ b/src/Microsoft.OData.Core/Json/JsonWriterExtensions.Async.cs
@@ -26,7 +26,7 @@ internal static partial class JsonWriterExtensions
/// Writes the given json object value to the underlying json writer.
/// Called when the top-level object is started to possibly inject first property into the object.
/// A task that represents the asynchronous write operation.
- internal static async Task WriteJsonObjectValueAsync(
+ internal static async ValueTask WriteJsonObjectValueAsync(
this IJsonWriter jsonWriter,
IDictionary jsonObjectValue,
Func injectPropertyDelegate)
@@ -56,7 +56,7 @@ internal static async Task WriteJsonObjectValueAsync(
/// The to write to.
/// The value to write.
/// A task that represents the asynchronous write operation.
- internal static Task WritePrimitiveValueAsync(this IJsonWriter jsonWriter, object value)
+ internal static ValueTask WritePrimitiveValueAsync(this IJsonWriter jsonWriter, object value)
{
if (value is bool)
{
@@ -140,7 +140,7 @@ internal static Task WritePrimitiveValueAsync(this IJsonWriter jsonWriter, objec
return jsonWriter.WriteValueAsync((TimeOfDay)value);
}
- return TaskUtils.GetFaultedTask(
+ return ValueTask.FromException(
new ODataException(ODataErrorStrings.ODataJsonWriter_UnsupportedValueType(value.GetType().FullName)));
}
@@ -150,7 +150,7 @@ internal static Task WritePrimitiveValueAsync(this IJsonWriter jsonWriter, objec
/// The to write to.
/// value to write.
/// A task that represents the asynchronous write operation.
- internal static Task WriteODataValueAsync(this IJsonWriter jsonWriter, ODataValue odataValue)
+ internal static ValueTask WriteODataValueAsync(this IJsonWriter jsonWriter, ODataValue odataValue)
{
if (odataValue == null || odataValue is ODataNullValue)
{
@@ -170,7 +170,7 @@ internal static Task WriteODataValueAsync(this IJsonWriter jsonWriter, ODataValu
{
return WriteODataResourceValueAsync(jsonWriter, resourceValue);
- async Task WriteODataResourceValueAsync(
+ async ValueTask WriteODataResourceValueAsync(
IJsonWriter innerJsonWriter,
ODataResourceValue innerResourceValue)
{
@@ -190,7 +190,7 @@ async Task WriteODataResourceValueAsync(
{
return WriteODataCollectionValueAsync(jsonWriter, collectionValue);
- async Task WriteODataCollectionValueAsync(
+ async ValueTask WriteODataCollectionValueAsync(
IJsonWriter innerJsonWriter,
ODataCollectionValue innerCollectionValue)
{
@@ -214,7 +214,7 @@ async Task WriteODataCollectionValueAsync(
}
}
- return TaskUtils.GetFaultedTask(
+ return ValueTask.FromException(
new ODataException(ODataErrorStrings.ODataJsonWriter_UnsupportedValueType(odataValue.GetType().FullName)));
}
@@ -224,7 +224,7 @@ async Task WriteODataCollectionValueAsync(
/// The to write to.
/// Writes the json array value to the underlying json writer.
/// A task that represents the asynchronous write operation.
- private static async Task WriteJsonArrayValueAsync(this IJsonWriter jsonWriter, IEnumerable arrayValue)
+ private static async ValueTask WriteJsonArrayValueAsync(this IJsonWriter jsonWriter, IEnumerable arrayValue)
{
Debug.Assert(arrayValue != null, "arrayValue != null");
@@ -244,7 +244,7 @@ private static async Task WriteJsonArrayValueAsync(this IJsonWriter jsonWriter,
/// The to write to.
/// value to write.
/// A task that represents the asynchronous write operation.
- private static Task WriteJsonValueAsync(this IJsonWriter jsonWriter, object propertyValue)
+ private static ValueTask WriteJsonValueAsync(this IJsonWriter jsonWriter, object propertyValue)
{
if (propertyValue == null)
{
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonBatchReader.cs b/src/Microsoft.OData.Core/Json/ODataJsonBatchReader.cs
index ee8ee6c467..cbe103224f 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonBatchReader.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonBatchReader.cs
@@ -370,7 +370,7 @@ protected override void ValidateDependsOnIds(string contentId, IEnumerable
- protected override async Task ReadAtStartImplementationAsync()
+ protected override async ValueTask ReadAtStartImplementationAsync()
{
Debug.Assert(this.State == ODataBatchReaderState.Initial, $"{nameof(this.State)} == {nameof(ODataBatchReaderState.Initial)}");
@@ -417,7 +417,7 @@ await this.StartReadingBatchArrayAsync()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the batch reader state after the read.
///
- protected override async Task ReadAtOperationImplementationAsync()
+ protected override async ValueTask ReadAtOperationImplementationAsync()
{
if (this.JsonInputContext.JsonReader.NodeType != JsonNodeType.StartObject)
{
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonBatchWriter.cs b/src/Microsoft.OData.Core/Json/ODataJsonBatchWriter.cs
index 6a8b11aeba..b9a7a046f2 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonBatchWriter.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonBatchWriter.cs
@@ -166,7 +166,7 @@ public override void StreamRequested()
/// A task representing any action that is running as part of the status change of the operation;
/// null if no such action exists.
///
- public override async Task StreamRequestedAsync()
+ public override async ValueTask StreamRequestedAsync()
{
// Write any pending data and flush the batch writer to the async buffered stream
await this.StartBatchOperationContentAsync()
@@ -196,7 +196,7 @@ public override void StreamDisposed()
///
/// This method is called to notify that the content stream of a batch operation has been disposed.
///
- public override async Task StreamDisposedAsync()
+ public override async ValueTask StreamDisposedAsync()
{
Debug.Assert(this.CurrentOperationMessage != null, "Expected non-null operation message!");
@@ -227,7 +227,7 @@ public override void OnInStreamError()
throw new ODataException(Strings.ODataBatchWriter_CannotWriteInStreamErrorForBatch);
}
- public override async Task OnInStreamErrorAsync()
+ public override async ValueTask OnInStreamErrorAsync()
{
this.JsonOutputContext.VerifyNotDisposed();
this.SetState(BatchWriterState.Error);
@@ -464,7 +464,7 @@ protected override void VerifyNotDisposed()
/// Asynchronously starts a new batch.
///
/// A task that represents the asynchronous write operation.
- protected override async Task WriteStartBatchImplementationAsync()
+ protected override async ValueTask WriteStartBatchImplementationAsync()
{
await WriteBatchEnvelopeAsync()
.ConfigureAwait(false);
@@ -475,7 +475,7 @@ await WriteBatchEnvelopeAsync()
/// Asynchronously ends a batch.
///
/// A task that represents the asynchronous write operation.
- protected override async Task WriteEndBatchImplementationAsync()
+ protected override async ValueTask WriteEndBatchImplementationAsync()
{
// write pending message data (headers, response line) for a previously unclosed message/request
await this.WritePendingMessageDataAsync(true)
@@ -498,7 +498,7 @@ await this.jsonWriter.EndObjectScopeAsync()
/// The atomic group id of the changeset to start.
/// If it is null for Json batch, an GUID will be generated and used as the atomic group id.
/// A task that represents the asynchronous write operation.
- protected override async Task WriteStartChangesetImplementationAsync(string groupId)
+ protected override async ValueTask WriteStartChangesetImplementationAsync(string groupId)
{
Debug.Assert(groupId != null, "groupId != null");
@@ -516,7 +516,7 @@ await this.WritePendingMessageDataAsync(true)
/// Asynchronously ends an active changeset.
///
/// A task that represents the asynchronous write operation.
- protected override async Task WriteEndChangesetImplementationAsync()
+ protected override async ValueTask WriteEndChangesetImplementationAsync()
{
// write pending message data (headers, response line) for a previously unclosed message/request
await this.WritePendingMessageDataAsync(true)
@@ -539,7 +539,7 @@ await this.WritePendingMessageDataAsync(true)
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains an
/// that can be used to write the request operation.
- protected override async Task CreateOperationRequestMessageImplementationAsync(
+ protected override async ValueTask CreateOperationRequestMessageImplementationAsync(
string method,
Uri uri,
string contentId,
@@ -620,7 +620,7 @@ await this.WriteRequestUriAsync(uri, payloadUriOption)
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains an
/// that can be used to write the response operation.
- protected override async Task CreateOperationResponseMessageImplementationAsync(string contentId)
+ protected override async ValueTask CreateOperationResponseMessageImplementationAsync(string contentId)
{
await this.WritePendingMessageDataAsync(true)
.ConfigureAwait(false);
@@ -908,7 +908,7 @@ private void WriteRequestUri(Uri uri, BatchPayloadUriOption payloadUriOption)
/// Asynchronously writes the start boundary for an operation. This is Json start object.
///
/// A task that represents the asynchronous write operation.
- private Task WriteStartBoundaryForOperationAsync()
+ private ValueTask WriteStartBoundaryForOperationAsync()
{
// Start the individual message object
return this.jsonWriter.StartObjectScopeAsync();
@@ -980,7 +980,7 @@ await this.EnsurePrecedingMessageIsClosedAsync()
/// Asynchronously closes preceding message Json object if any.
///
/// A task that represents the asynchronous write operation.
- private Task EnsurePrecedingMessageIsClosedAsync()
+ private ValueTask EnsurePrecedingMessageIsClosedAsync()
{
// There shouldn't be any pending message object.
Debug.Assert(this.CurrentOperationMessage == null, "this.CurrentOperationMessage == null");
@@ -992,7 +992,7 @@ private Task EnsurePrecedingMessageIsClosedAsync()
/// Always sets the isBatchEnvelopeWritten flag to true before return.
///
/// A task that represents the asynchronous write operation.
- private async Task WriteBatchEnvelopeAsync()
+ private async ValueTask WriteBatchEnvelopeAsync()
{
// Start the top level scope
await this.jsonWriter.StartObjectScopeAsync()
@@ -1009,7 +1009,7 @@ await this.jsonWriter.StartArrayScopeAsync()
/// Asynchronously writes pending data for the current request message.
///
/// A task that represents the asynchronous write operation.
- private async Task WritePendingRequestMessageDataAsync()
+ private async ValueTask WritePendingRequestMessageDataAsync()
{
Debug.Assert(this.CurrentOperationRequestMessage != null, "this.CurrentOperationRequestMessage != null");
@@ -1038,7 +1038,7 @@ await this.jsonWriter.EndObjectScopeAsync()
/// Asynchronously writes pending data for the current response message.
///
/// A task that represents the asynchronous write operation.
- private async Task WritePendingResponseMessageDataAsync()
+ private async ValueTask WritePendingResponseMessageDataAsync()
{
Debug.Assert(this.JsonOutputContext.WritingResponse, "If the response message is available we must be writing response.");
Debug.Assert(this.CurrentOperationResponseMessage != null, "this.CurrentOperationResponseMessage != null");
@@ -1093,7 +1093,7 @@ await this.jsonWriter.EndObjectScopeAsync()
/// The format of operation Request-URI, which could be AbsoluteUri, AbsoluteResourcePathAndHost, or RelativeResourcePath.
///
/// A task that represents the asynchronous write operation.
- private async Task WriteRequestUriAsync(Uri uri, BatchPayloadUriOption payloadUriOption)
+ private async ValueTask WriteRequestUriAsync(Uri uri, BatchPayloadUriOption payloadUriOption)
{
await this.jsonWriter.WriteNameAsync(PropertyUrl)
.ConfigureAwait(false);
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonCollectionReader.cs b/src/Microsoft.OData.Core/Json/ODataJsonCollectionReader.cs
index 407a743d96..4ddae06579 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonCollectionReader.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonCollectionReader.cs
@@ -78,7 +78,7 @@ protected override bool ReadAtStartImplementation()
/// Pre-Condition: JsonNodeType.None: assumes that the JSON reader has not been used yet when not reading a nested payload.
/// Post-Condition: The reader is positioned on the first node of the first item or the EndArray node of an empty item array
///
- protected override async Task ReadAtStartImplementationAsync()
+ protected override async ValueTask ReadAtStartImplementationAsync()
{
Debug.Assert(this.State == ODataCollectionReaderState.Start, "this.State == ODataCollectionReaderState.Start");
Debug.Assert(this.IsReadingNestedPayload || this.jsonCollectionDeserializer.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None when not reading a nested payload.");
@@ -126,7 +126,7 @@ protected override bool ReadAtCollectionStartImplementation()
/// JsonNodeType.PrimitiveValue: for a primitive value as first item
/// Post-Condition: The reader is positioned on the first node of the second item or an EndArray node if there are no items in the collection
///
- protected override Task ReadAtCollectionStartImplementationAsync()
+ protected override ValueTask ReadAtCollectionStartImplementationAsync()
{
return this.ReadAtCollectionStartImplementationAsynchronously();
}
@@ -160,7 +160,7 @@ protected override bool ReadAtValueImplementation()
/// JsonNodeType.PrimitiveValue: for a primitive item
/// Post-Condition: The reader is positioned on the first node of the next item or an EndArray node if there are no items in the collection
///
- protected override Task ReadAtValueImplementationAsync()
+ protected override ValueTask ReadAtValueImplementationAsync()
{
return this.ReadAtValueImplementationAsynchronously();
}
@@ -186,7 +186,7 @@ protected override bool ReadAtCollectionEndImplementation()
/// Pre-Condition: JsonNodeType.EndArray the end of the item array of the collection
/// Post-Condition: JsonNodeType.EndOfInput nothing else to read when not reading a nested payload
///
- protected override Task ReadAtCollectionEndImplementationAsync()
+ protected override ValueTask ReadAtCollectionEndImplementationAsync()
{
return this.ReadAtCollectionEndImplementationAsynchronously();
}
@@ -371,7 +371,7 @@ await this.jsonCollectionDeserializer.JsonReader.ReadStartArrayAsync()
/// JsonNodeType.PrimitiveValue: for a primitive value as first item
/// Post-Condition: The reader is positioned on the first node of the second item or an EndArray node if there are no items in the collection
///
- private async Task ReadAtCollectionStartImplementationAsynchronously()
+ private async ValueTask ReadAtCollectionStartImplementationAsynchronously()
{
Debug.Assert(this.State == ODataCollectionReaderState.CollectionStart, "this.State == ODataCollectionReaderState.CollectionStart");
@@ -406,7 +406,7 @@ private async Task ReadAtCollectionStartImplementationAsynchronously()
/// JsonNodeType.PrimitiveValue: for a primitive item
/// Post-Condition: The reader is positioned on the first node of the next item or an EndArray node if there are no items in the collection
///
- private async Task ReadAtValueImplementationAsynchronously()
+ private async ValueTask ReadAtValueImplementationAsynchronously()
{
Debug.Assert(this.State == ODataCollectionReaderState.Value, "this.State == ODataCollectionReaderState.Value");
@@ -438,7 +438,7 @@ private async Task ReadAtValueImplementationAsynchronously()
/// Pre-Condition: JsonNodeType.EndArray the end of the item array of the collection
/// Post-Condition: JsonNodeType.EndOfInput nothing else to read when not reading a nested payload
///
- private async Task ReadAtCollectionEndImplementationAsynchronously()
+ private async ValueTask ReadAtCollectionEndImplementationAsynchronously()
{
Debug.Assert(this.State == ODataCollectionReaderState.CollectionEnd, "this.State == ODataCollectionReaderState.CollectionEnd");
Debug.Assert(this.jsonCollectionDeserializer.JsonReader.NodeType == JsonNodeType.EndArray, "Pre-Condition: expected JsonNodeType.EndArray");
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonCollectionSerializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonCollectionSerializer.cs
index 3efd1c628c..a90bde227b 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonCollectionSerializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonCollectionSerializer.cs
@@ -94,7 +94,7 @@ internal void WriteCollectionEnd()
///
/// The collection start to write.
/// The item type of the collection or null if no metadata is available.
- internal async Task WriteCollectionStartAsync(ODataCollectionStart collectionStart, IEdmTypeReference itemTypeReference)
+ internal async ValueTask WriteCollectionStartAsync(ODataCollectionStart collectionStart, IEdmTypeReference itemTypeReference)
{
Debug.Assert(collectionStart != null, "collectionStart != null");
@@ -145,7 +145,7 @@ await this.JsonWriter.StartArrayScopeAsync()
///
/// Asynchronously writes the end of a collection.
///
- internal async Task WriteCollectionEndAsync()
+ internal async ValueTask WriteCollectionEndAsync()
{
// Write the end of the array for the collection items
// "]"
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonCollectionWriter.cs b/src/Microsoft.OData.Core/Json/ODataJsonCollectionWriter.cs
index 2c6ec3dc32..80642068b0 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonCollectionWriter.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonCollectionWriter.cs
@@ -170,7 +170,7 @@ protected override void WriteCollectionItem(object item, IEdmTypeReference expec
/// Asynchronously start writing an OData payload.
///
/// A task that represents the asynchronous write operation.
- protected override Task StartPayloadAsync()
+ protected override ValueTask StartPayloadAsync()
{
return this.jsonCollectionSerializer.WritePayloadStartAsync();
}
@@ -179,7 +179,7 @@ protected override Task StartPayloadAsync()
/// Asynchronously finish writing an OData payload.
///
/// A task that represents the asynchronous write operation.
- protected override Task EndPayloadAsync()
+ protected override ValueTask EndPayloadAsync()
{
return this.jsonCollectionSerializer.WritePayloadEndAsync();
}
@@ -189,7 +189,7 @@ protected override Task EndPayloadAsync()
///
/// The representing the collection.
/// A task that represents the asynchronous write operation.
- protected override Task StartCollectionAsync(ODataCollectionStart collectionStart)
+ protected override ValueTask StartCollectionAsync(ODataCollectionStart collectionStart)
{
return this.jsonCollectionSerializer.WriteCollectionStartAsync(collectionStart, this.ItemTypeReference);
}
@@ -198,7 +198,7 @@ protected override Task StartCollectionAsync(ODataCollectionStart collectionStar
/// Asynchronously finish writing a collection.
///
/// A task that represents the asynchronous write operation.
- protected override Task EndCollectionAsync()
+ protected override ValueTask EndCollectionAsync()
{
this.jsonCollectionSerializer.ReturnDuplicatePropertyNameChecker(this.DuplicatePropertyNameChecker);
@@ -211,7 +211,7 @@ protected override Task EndCollectionAsync()
/// The collection item to write.
/// The expected type of the collection item or null if no expected item type exists.
/// A task that represents the asynchronous write operation.
- protected override async Task WriteCollectionItemAsync(object item, IEdmTypeReference expectedItemType)
+ protected override async ValueTask WriteCollectionItemAsync(object item, IEdmTypeReference expectedItemType)
{
if (item == null)
{
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonDeltaReader.cs b/src/Microsoft.OData.Core/Json/ODataJsonDeltaReader.cs
index 9d2f1f5dab..afa2c615a0 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonDeltaReader.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonDeltaReader.cs
@@ -175,7 +175,7 @@ public override bool Read()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains true if more items were read; otherwise false.
///
- public override async Task ReadAsync()
+ public override async ValueTask ReadAsync()
{
bool result = await this.underlyingReader.ReadAsync()
.ConfigureAwait(false);
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonDeltaWriter.cs b/src/Microsoft.OData.Core/Json/ODataJsonDeltaWriter.cs
index 5cda34bb73..08d3936ab4 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonDeltaWriter.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonDeltaWriter.cs
@@ -120,7 +120,7 @@ public override void WriteStart(ODataDeltaResourceSet deltaResourceSet)
///
/// Delta resource set/collection to write.
/// A task instance that represents the asynchronous write operation.
- public override Task WriteStartAsync(ODataDeltaResourceSet deltaResourceSet)
+ public override ValueTask WriteStartAsync(ODataDeltaResourceSet deltaResourceSet)
{
return this.resourceWriter.WriteStartAsync(deltaResourceSet);
}
@@ -137,7 +137,7 @@ public override void WriteEnd()
/// Asynchronously finish writing a delta resource set.
///
/// A task instance that represents the asynchronous write operation.
- public override Task WriteEndAsync()
+ public override ValueTask WriteEndAsync()
{
return this.resourceWriter.WriteEndAsync();
}
@@ -156,7 +156,7 @@ public override void WriteStart(ODataNestedResourceInfo nestedResourceInfo)
///
/// The nested resource info to write.
/// A task instance that represents the asynchronous write operation.
- public override Task WriteStartAsync(ODataNestedResourceInfo nestedResourceInfo)
+ public override ValueTask WriteStartAsync(ODataNestedResourceInfo nestedResourceInfo)
{
return this.resourceWriter.WriteStartAsync(nestedResourceInfo);
}
@@ -175,7 +175,7 @@ public override void WriteStart(ODataResourceSet expandedResourceSet)
///
/// The expanded resource set to write.
/// A task instance that represents the asynchronous write operation.
- public override Task WriteStartAsync(ODataResourceSet expandedResourceSet)
+ public override ValueTask WriteStartAsync(ODataResourceSet expandedResourceSet)
{
return this.resourceWriter.WriteStartAsync(expandedResourceSet);
}
@@ -194,7 +194,7 @@ public override void WriteStart(ODataResource deltaResource)
///
/// The delta resource to write.
/// A task instance that represents the asynchronous write operation.
- public override Task WriteStartAsync(ODataResource deltaResource)
+ public override ValueTask WriteStartAsync(ODataResource deltaResource)
{
return this.resourceWriter.WriteStartAsync(deltaResource);
}
@@ -214,7 +214,7 @@ public override void WriteDeltaDeletedEntry(ODataDeltaDeletedEntry deltaDeletedE
///
/// The delta deleted resource to write.
/// A task instance that represents the asynchronous write operation.
- public override Task WriteDeltaDeletedEntryAsync(ODataDeltaDeletedEntry deltaDeletedEntry)
+ public override ValueTask WriteDeltaDeletedEntryAsync(ODataDeltaDeletedEntry deltaDeletedEntry)
{
return this.resourceWriter.WriteStartAsync(ODataDeltaDeletedEntry.GetDeletedResource(deltaDeletedEntry));
}
@@ -233,7 +233,7 @@ public override void WriteDeltaLink(ODataDeltaLink deltaLink)
///
/// The delta link to write.
/// A task instance that represents the asynchronous write operation.
- public override Task WriteDeltaLinkAsync(ODataDeltaLink deltaLink)
+ public override ValueTask WriteDeltaLinkAsync(ODataDeltaLink deltaLink)
{
return this.resourceWriter.WriteDeltaLinkAsync(deltaLink);
}
@@ -252,7 +252,7 @@ public override void WriteDeltaDeletedLink(ODataDeltaDeletedLink deltaDeletedLin
///
/// The delta deleted link to write.
/// A task instance that represents the asynchronous write operation.
- public override Task WriteDeltaDeletedLinkAsync(ODataDeltaDeletedLink deltaDeletedLink)
+ public override ValueTask WriteDeltaDeletedLinkAsync(ODataDeltaDeletedLink deltaDeletedLink)
{
return this.resourceWriter.WriteDeltaDeletedLinkAsync(deltaDeletedLink);
}
@@ -287,7 +287,7 @@ void IODataOutputInStreamErrorListener.OnInStreamError()
}
///
- Task IODataOutputInStreamErrorListener.OnInStreamErrorAsync()
+ ValueTask IODataOutputInStreamErrorListener.OnInStreamErrorAsync()
{
return this.inStreamErrorListener.OnInStreamErrorAsync();
}
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonEntityReferenceLinkDeserializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonEntityReferenceLinkDeserializer.cs
index 734b9e86b5..cf185b1dc6 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonEntityReferenceLinkDeserializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonEntityReferenceLinkDeserializer.cs
@@ -60,7 +60,7 @@ internal ODataEntityReferenceLinks ReadEntityReferenceLinks()
/// Read a set of top-level entity reference links.
///
/// A task which returns an representing the read links.
- internal async Task ReadEntityReferenceLinksAsync()
+ internal async ValueTask ReadEntityReferenceLinksAsync()
{
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet.");
this.JsonReader.AssertNotBuffering();
@@ -118,7 +118,7 @@ internal ODataEntityReferenceLink ReadEntityReferenceLink()
/// Reads a top-level entity reference link - implementation of the actual functionality.
///
/// A task which returns an representing the read entity reference link.
- internal async Task ReadEntityReferenceLinkAsync()
+ internal async ValueTask ReadEntityReferenceLinkAsync()
{
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet.");
this.JsonReader.AssertNotBuffering();
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonErrorDeserializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonErrorDeserializer.cs
index ffd7c9e6e6..5a10701e64 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonErrorDeserializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonErrorDeserializer.cs
@@ -79,7 +79,7 @@ internal ODataError ReadTopLevelError()
/// Pre-Condition: JsonNodeType.None - The reader must not have been used yet.
/// Post-Condition: JsonNodeType.EndOfInput
///
- internal async Task ReadTopLevelErrorAsync()
+ internal async ValueTask ReadTopLevelErrorAsync()
{
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet.");
Debug.Assert(!this.JsonReader.DisableInStreamErrorDetection, "!JsonReader.DisableInStreamErrorDetection");
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonFormat.cs b/src/Microsoft.OData.Core/Json/ODataJsonFormat.cs
index 6fc20a0b19..2308662c96 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonFormat.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonFormat.cs
@@ -79,7 +79,7 @@ public override ODataOutputContext CreateOutputContext(
/// Configuration settings of the OData reader.
/// A task that when completed returns the set of s
/// that are supported with the specified payload.
- public override Task> DetectPayloadKindAsync(
+ public override ValueTask> DetectPayloadKindAsync(
ODataMessageInfo messageInfo,
ODataMessageReaderSettings settings)
{
@@ -93,14 +93,14 @@ public override Task> DetectPayloadKindAsync(
/// The context information for the message.
/// Configuration settings of the OData reader.
/// Task which when completed returned the newly created input context.
- public override Task CreateInputContextAsync(
+ public override ValueTask CreateInputContextAsync(
ODataMessageInfo messageInfo,
ODataMessageReaderSettings messageReaderSettings)
{
ExceptionUtils.CheckArgumentNotNull(messageInfo, "messageInfo");
ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings");
- return Task.FromResult(
+ return ValueTask.FromResult(
new ODataJsonInputContext(messageInfo, messageReaderSettings));
}
@@ -110,14 +110,14 @@ public override Task CreateInputContextAsync(
/// The context information for the message.
/// Configuration settings of the OData writer.
/// Task which represents the pending create operation.
- public override Task CreateOutputContextAsync(
+ public override ValueTask CreateOutputContextAsync(
ODataMessageInfo messageInfo,
ODataMessageWriterSettings messageWriterSettings)
{
ExceptionUtils.CheckArgumentNotNull(messageInfo, "messageInfo");
ExceptionUtils.CheckArgumentNotNull(messageWriterSettings, "messageWriterSettings");
- return Task.FromResult(
+ return ValueTask.FromResult(
new ODataJsonOutputContext(messageInfo, messageWriterSettings));
}
@@ -145,18 +145,16 @@ private static IEnumerable DetectPayloadKindImplementation(
/// The context information for the message.
/// Configuration settings of the OData reader.
/// An enumerable of zero, one or more payload kinds that were detected from looking at the payload in the message stream.
- private static Task> DetectPayloadKindImplementationAsync(
+ private static async ValueTask> DetectPayloadKindImplementationAsync(
ODataMessageInfo messageInfo,
ODataMessageReaderSettings settings)
{
var detectionInfo = new ODataPayloadKindDetectionInfo(messageInfo, settings);
messageInfo.Encoding = detectionInfo.GetEncoding();
- var jsonInputContext = new ODataJsonInputContext(messageInfo, settings);
- return jsonInputContext.DetectPayloadKindAsync(detectionInfo)
- .FollowAlwaysWith(t =>
- {
- jsonInputContext.Dispose();
- });
+ await using var jsonInputContext = new ODataJsonInputContext(messageInfo, settings);
+
+ IEnumerable result = await jsonInputContext.DetectPayloadKindAsync(detectionInfo);
+ return result;
}
}
}
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonInputContext.cs b/src/Microsoft.OData.Core/Json/ODataJsonInputContext.cs
index 41bfebef63..0cbf28cffe 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonInputContext.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonInputContext.cs
@@ -186,13 +186,19 @@ public override ODataReader CreateResourceSetReader(IEdmEntitySetBase entitySet,
/// The entity set we are going to read resources for.
/// The expected structured type for the items in the resource set.
/// Task which when completed returns the newly created .
- public override Task CreateResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
+ public override ValueTask CreateResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
{
this.AssertAsynchronous();
this.VerifyCanCreateODataReader(entitySet, expectedResourceType);
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
- return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateResourceSetReaderImplementation(entitySet, expectedResourceType, /*readingParameter*/ false, /*readingDelta*/ false));
+ return ValueTask.FromResult(
+ this.CreateResourceSetReaderImplementation(
+ entitySet,
+ expectedResourceType,
+ readingParameter: false,
+ readingDelta: false)
+ );
}
///
@@ -215,13 +221,19 @@ public override ODataReader CreateDeltaResourceSetReader(IEdmEntitySetBase entit
/// The entity set we are going to read resources for.
/// The expected structured type for the items in the resource set.
/// Task which when completed returns the newly created .
- public override Task CreateDeltaResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
+ public override ValueTask CreateDeltaResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
{
this.AssertAsynchronous();
this.VerifyCanCreateODataReader(entitySet, expectedResourceType);
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
- return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateResourceSetReaderImplementation(entitySet, expectedResourceType, /*readingParameter*/ false, /*readingDelta*/ true));
+ return ValueTask.FromResult(
+ this.CreateResourceSetReaderImplementation(
+ entitySet,
+ expectedResourceType,
+ readingParameter: false,
+ readingDelta: true)
+ );
}
///
@@ -244,13 +256,14 @@ public override ODataReader CreateResourceReader(IEdmNavigationSource navigation
/// The navigation source we are going to read resources for.
/// The expected structured type for the resource to be read.
/// Task which when completed returns the newly created .
- public override Task CreateResourceReaderAsync(IEdmNavigationSource navigationSource, IEdmStructuredType expectedResourceType)
+ public override ValueTask CreateResourceReaderAsync(IEdmNavigationSource navigationSource, IEdmStructuredType expectedResourceType)
{
this.AssertAsynchronous();
this.VerifyCanCreateODataReader(navigationSource, expectedResourceType);
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
- return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateResourceReaderImplementation(navigationSource, expectedResourceType));
+ return ValueTask.FromResult(
+ this.CreateResourceReaderImplementation(navigationSource, expectedResourceType));
}
///
@@ -271,13 +284,13 @@ public override ODataCollectionReader CreateCollectionReader(IEdmTypeReference e
///
/// The expected type reference for the items in the collection.
/// Task which when completed returns the newly create .
- public override Task CreateCollectionReaderAsync(IEdmTypeReference expectedItemTypeReference)
+ public override ValueTask CreateCollectionReaderAsync(IEdmTypeReference expectedItemTypeReference)
{
this.AssertAsynchronous();
this.VerifyCanCreateCollectionReader(expectedItemTypeReference);
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
- return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateCollectionReaderImplementation(expectedItemTypeReference));
+ return ValueTask.FromResult(this.CreateCollectionReaderImplementation(expectedItemTypeReference));
}
///
@@ -303,7 +316,7 @@ public override ODataProperty ReadProperty(IEdmStructuralProperty property, IEdm
/// The producing the property to be read.
/// The expected type reference of the property to read.
/// Task which when completed returns an representing the read property.
- public override Task ReadPropertyAsync(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
+ public override ValueTask ReadPropertyAsync(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
{
this.AssertAsynchronous();
this.VerifyCanReadProperty();
@@ -329,7 +342,7 @@ public override ODataError ReadError()
/// Asynchronously read a top-level error.
///
/// Task which when completed returns an representing the read error.
- public override Task ReadErrorAsync()
+ public override ValueTask ReadErrorAsync()
{
this.AssertAsynchronous();
@@ -357,12 +370,18 @@ public override ODataReader CreateUriParameterResourceSetReader(IEdmEntitySetBas
/// The entity set we are going to read resources for.
/// The expected structured type for the items in the resource set.
/// Task which when completed returns the newly created .
- public override Task CreateUriParameterResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
+ public override ValueTask CreateUriParameterResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
{
this.AssertAsynchronous();
this.VerifyCanCreateODataReader(entitySet, expectedResourceType);
- return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateResourceSetReaderImplementation(entitySet, expectedResourceType, /*readingParameter*/ true, /*readingDelta*/ false));
+ return ValueTask.FromResult(
+ this.CreateResourceSetReaderImplementation(
+ entitySet,
+ expectedResourceType,
+ readingParameter: true,
+ readingDelta: false)
+ );
}
///
@@ -382,7 +401,7 @@ public override ODataReader CreateUriParameterResourceReader(IEdmNavigationSourc
/// The navigation source we are going to read resources for.
/// The expected structured type for the resource to be read.
/// Task which when completed returns the newly created .
- public override Task CreateUriParameterResourceReaderAsync(IEdmNavigationSource navigationSource, IEdmStructuredType expectedResourceType)
+ public override ValueTask CreateUriParameterResourceReaderAsync(IEdmNavigationSource navigationSource, IEdmStructuredType expectedResourceType)
{
return this.CreateResourceReaderAsync(navigationSource, expectedResourceType);
}
@@ -405,13 +424,13 @@ public override ODataParameterReader CreateParameterReader(IEdmOperation operati
///
/// The operation whose parameters are being read.
/// Task which when completed returns the newly created .
- public override Task CreateParameterReaderAsync(IEdmOperation operation)
+ public override ValueTask CreateParameterReaderAsync(IEdmOperation operation)
{
this.AssertAsynchronous();
this.VerifyCanCreateParameterReader(operation);
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
- return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateParameterReaderImplementation(operation));
+ return ValueTask.FromResult(this.CreateParameterReaderImplementation(operation));
}
///
@@ -433,7 +452,7 @@ public IEnumerable DetectPayloadKind(ODataPayloadKindDetection
///
/// Additional information available for the payload kind detection.
/// A task which returns an enumerable of zero, one or more payload kinds that were detected from looking at the payload in the message stream.
- public Task> DetectPayloadKindAsync(ODataPayloadKindDetectionInfo detectionInfo)
+ public ValueTask> DetectPayloadKindAsync(ODataPayloadKindDetectionInfo detectionInfo)
{
Debug.Assert(detectionInfo != null, "detectionInfo != null");
this.VerifyCanDetectPayloadKind();
@@ -462,13 +481,13 @@ internal override ODataDeltaReader CreateDeltaReader(IEdmEntitySetBase entitySet
/// The entity set we are going to read entities for.
/// The expected base entity type for the entries in the delta response.
/// Task which when completed returns the newly created .
- internal override Task CreateDeltaReaderAsync(IEdmEntitySetBase entitySet, IEdmEntityType expectedBaseEntityType)
+ internal override ValueTask CreateDeltaReaderAsync(IEdmEntitySetBase entitySet, IEdmEntityType expectedBaseEntityType)
{
this.AssertAsynchronous();
this.VerifyCanCreateODataReader(entitySet, expectedBaseEntityType);
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
- return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateDeltaReaderImplementation(entitySet, expectedBaseEntityType));
+ return ValueTask.FromResult(this.CreateDeltaReaderImplementation(entitySet, expectedBaseEntityType));
}
///
@@ -484,10 +503,10 @@ internal override ODataBatchReader CreateBatchReader()
/// Asynchronously create a .
///
/// Task which when completed returns the newly created .
- internal override Task CreateBatchReaderAsync()
+ internal override ValueTask CreateBatchReaderAsync()
{
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
- return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateBatchReaderImplementation(/*synchronous*/ false));
+ return ValueTask.FromResult(this.CreateBatchReaderImplementation(synchronous: false));
}
///
@@ -510,7 +529,7 @@ internal override ODataServiceDocument ReadServiceDocument()
/// an that represents the read service document.
///
/// Task which when completed returns an representing the read service document.
- internal override Task ReadServiceDocumentAsync()
+ internal override ValueTask ReadServiceDocumentAsync()
{
this.AssertAsynchronous();
@@ -534,7 +553,7 @@ internal override ODataEntityReferenceLinks ReadEntityReferenceLinks()
/// Asynchronously read a set of top-level entity reference links.
///
/// Task which when completed returns an representing the read links.
- internal override Task ReadEntityReferenceLinksAsync()
+ internal override ValueTask ReadEntityReferenceLinksAsync()
{
this.AssertAsynchronous();
@@ -559,7 +578,7 @@ internal override ODataEntityReferenceLink ReadEntityReferenceLink()
/// Asynchronously read a top-level entity reference link.
///
/// Task which when completed returns an representing the read entity reference link.
- internal override Task ReadEntityReferenceLinkAsync()
+ internal override ValueTask ReadEntityReferenceLinkAsync()
{
this.AssertAsynchronous();
this.VerifyCanReadEntityReferenceLink();
@@ -595,6 +614,27 @@ protected override void Dispose(bool disposing)
base.Dispose(disposing);
}
+ protected override ValueTask DisposeAsyncCore()
+ {
+ try
+ {
+ this.stream = null;
+
+ if (this.textReader != null)
+ {
+ // TextReader does not implement IAsyncDisposable
+ this.textReader.Dispose();
+ }
+
+ return base.DisposeAsyncCore();
+ }
+ finally
+ {
+ this.textReader = null;
+ this.jsonReader = null;
+ }
+ }
+
///
/// Helper method to create a TextReader over the message stream. This is needed by the constructor to dispose the message stream if the creation fails
/// since this is called from the constructor in place where exception handling is not possible.
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonOutputContext.cs b/src/Microsoft.OData.Core/Json/ODataJsonOutputContext.cs
index b555482719..a150be3f4b 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonOutputContext.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonOutputContext.cs
@@ -220,21 +220,17 @@ public override ODataWriter CreateODataResourceSetWriter(IEdmEntitySetBase entit
/// The resource type for the items in the resource set to be written (or null if the entity set base type should be used).
/// A running task for the created writer.
/// The write must flush the output when it's finished (inside the last Write call).
- public override Task CreateODataResourceSetWriterAsync(IEdmEntitySetBase entitySet, IEdmStructuredType resourceType)
+ public override ValueTask CreateODataResourceSetWriterAsync(IEdmEntitySetBase entitySet, IEdmStructuredType resourceType)
{
this.AssertAsynchronous();
- return TaskUtils.GetTaskForSynchronousOperation((
- thisParam,
- entitySetParam,
- resourceTypeParam) => thisParam.CreateODataResourceSetWriterImplementation(
- entitySetParam,
- resourceTypeParam,
+ return ValueTask.FromResult(
+ this.CreateODataResourceSetWriterImplementation(
+ entitySet,
+ resourceType,
writingParameter: false,
- writingDelta: false),
- this,
- entitySet,
- resourceType);
+ writingDelta:false)
+ );
}
///
@@ -258,21 +254,17 @@ public override ODataWriter CreateODataDeltaResourceSetWriter(IEdmEntitySetBase
/// The resource type for the items in the resource set to be written (or null if the entity set base type should be used).
/// A running task for the created writer.
/// The write must flush the output when it's finished (inside the last Write call).
- public override Task CreateODataDeltaResourceSetWriterAsync(IEdmEntitySetBase entitySet, IEdmStructuredType resourceType)
+ public override ValueTask CreateODataDeltaResourceSetWriterAsync(IEdmEntitySetBase entitySet, IEdmStructuredType resourceType)
{
this.AssertAsynchronous();
- return TaskUtils.GetTaskForSynchronousOperation((
- thisParam,
- entitySetParam,
- resourceTypeParam) => thisParam.CreateODataResourceSetWriterImplementation(
- entitySetParam,
- resourceTypeParam,
+ return ValueTask.FromResult(
+ this.CreateODataResourceSetWriterImplementation(
+ entitySet,
+ resourceType,
writingParameter: false,
- writingDelta: true),
- this,
- entitySet,
- resourceType);
+ writingDelta: true)
+ );
}
///
@@ -296,19 +288,15 @@ public override ODataWriter CreateODataResourceWriter(IEdmNavigationSource navig
/// The structured type for the resources in the resource set to be written (or null if the entity set base type should be used).
/// A running task for the created writer.
/// The write must flush the output when it's finished (inside the last Write call).
- public override Task CreateODataResourceWriterAsync(IEdmNavigationSource navigationSource, IEdmStructuredType resourceType)
+ public override ValueTask CreateODataResourceWriterAsync(IEdmNavigationSource navigationSource, IEdmStructuredType resourceType)
{
this.AssertAsynchronous();
- return TaskUtils.GetTaskForSynchronousOperation((
- thisParam,
- navigationSourceParam,
- resourceTypeParam) => thisParam.CreateODataResourceWriterImplementation(
- navigationSourceParam,
- resourceTypeParam),
- this,
- navigationSource,
- resourceType);
+ return ValueTask.FromResult(
+ this.CreateODataResourceWriterImplementation(
+ navigationSource,
+ resourceType)
+ );
}
///
@@ -330,16 +318,12 @@ public override ODataCollectionWriter CreateODataCollectionWriter(IEdmTypeRefere
/// The item type of the collection being written or null if no metadata is available.
/// A running task for the created collection writer.
/// The write must flush the output when it's finished (inside the last Write call).
- public override Task CreateODataCollectionWriterAsync(IEdmTypeReference itemTypeReference)
+ public override ValueTask CreateODataCollectionWriterAsync(IEdmTypeReference itemTypeReference)
{
this.AssertAsynchronous();
- return TaskUtils.GetTaskForSynchronousOperation((
- thisParam,
- itemTypeReferenceParam) => thisParam.CreateODataCollectionWriterImplementation(
- itemTypeReferenceParam),
- this,
- itemTypeReference);
+ return ValueTask.FromResult(
+ this.CreateODataCollectionWriterImplementation(itemTypeReference));
}
///
@@ -361,7 +345,7 @@ public override ODataWriter CreateODataUriParameterResourceWriter(IEdmNavigation
/// The structured type for the resources in the resource set to be written.
/// A running task for the created writer.
/// The write must flush the output when it's finished (inside the last Write call).
- public override Task CreateODataUriParameterResourceWriterAsync(IEdmNavigationSource navigationSource, IEdmStructuredType resourceType)
+ public override ValueTask CreateODataUriParameterResourceWriterAsync(IEdmNavigationSource navigationSource, IEdmStructuredType resourceType)
{
return this.CreateODataResourceWriterAsync(navigationSource, resourceType);
}
@@ -387,21 +371,16 @@ public override ODataWriter CreateODataUriParameterResourceSetWriter(IEdmEntityS
/// The resource type for the items in the resource set to be written (or null if the entity set base type should be used).
/// A running task for the created writer.
/// The write must flush the output when it's finished (inside the last Write call).
- public override Task CreateODataUriParameterResourceSetWriterAsync(IEdmEntitySetBase entitySet, IEdmStructuredType resourceType)
+ public override ValueTask CreateODataUriParameterResourceSetWriterAsync(IEdmEntitySetBase entitySet, IEdmStructuredType resourceType)
{
this.AssertAsynchronous();
- return TaskUtils.GetTaskForSynchronousOperation((
- thisParam,
- entitySetParam,
- resourceTypeParam) => thisParam.CreateODataResourceSetWriterImplementation(
- entitySetParam,
- resourceTypeParam,
+ return ValueTask.FromResult(
+ this.CreateODataResourceSetWriterImplementation(
+ entitySet,
+ resourceType,
writingParameter: true,
- writingDelta: false),
- this,
- entitySet,
- resourceType);
+ writingDelta: false));
}
///
@@ -423,16 +402,11 @@ public override ODataParameterWriter CreateODataParameterWriter(IEdmOperation op
/// The operation import whose parameters will be written.
/// A running task for the created parameter writer.
/// The write must flush the output when it's finished (inside the last Write call).
- public override Task CreateODataParameterWriterAsync(IEdmOperation operation)
+ public override ValueTask CreateODataParameterWriterAsync(IEdmOperation operation)
{
this.AssertAsynchronous();
- return TaskUtils.GetTaskForSynchronousOperation((
- thisParam,
- operationParam) => thisParam.CreateODataParameterWriterImplementation(
- operationParam),
- this,
- operation);
+ return ValueTask.FromResult(this.CreateODataParameterWriterImplementation(operation));
}
///
@@ -454,7 +428,7 @@ public override void WriteProperty(ODataProperty property)
/// The property to write
/// A task representing the asynchronous operation of writing the property.
/// It is the responsibility of this method to flush the output before the task finishes.
- public override async Task WritePropertyAsync(ODataProperty property)
+ public override async ValueTask WritePropertyAsync(ODataProperty property)
{
this.AssertAsynchronous();
@@ -491,7 +465,7 @@ public override void WriteError(ODataError error, bool includeDebugInformation)
///
/// A task representing the asynchronous operation of writing the error.
/// It is the responsibility of this method to flush the output before the task finishes.
- public override async Task WriteErrorAsync(ODataError error, bool includeDebugInformation)
+ public override async ValueTask WriteErrorAsync(ODataError error, bool includeDebugInformation)
{
this.AssertAsynchronous();
@@ -570,7 +544,7 @@ internal Task FlushBuffersAsync()
return this.asynchronousOutputStream.FlushAsync();
}
- return TaskUtils.CompletedTask;
+ return Task.CompletedTask;
}
///
@@ -603,13 +577,11 @@ internal override ODataBatchWriter CreateODataBatchWriter()
/// A running task for the created batch writer.
/// We don't plan to make this public!
/// The write must flush the output when it's finished (inside the last Write call).
- internal override Task CreateODataBatchWriterAsync()
+ internal override ValueTask CreateODataBatchWriterAsync()
{
this.AssertAsynchronous();
- return TaskUtils.GetTaskForSynchronousOperation(
- thisParam => thisParam.CreateODataBatchWriterImplementation(),
- this);
+ return ValueTask.FromResult(this.CreateODataBatchWriterImplementation());
}
///
@@ -653,7 +625,7 @@ internal override void WriteInStreamError(ODataError error, bool includeDebugInf
/// the in-stream error is written.
/// It is the responsibility of this method to flush the output before the task finishes.
///
- internal override async Task WriteInStreamErrorAsync(ODataError error, bool includeDebugInformation)
+ internal override async ValueTask WriteInStreamErrorAsync(ODataError error, bool includeDebugInformation)
{
this.AssertAsynchronous();
@@ -683,19 +655,11 @@ internal override ODataDeltaWriter CreateODataDeltaWriter(IEdmEntitySetBase enti
/// The entity type for the entries in the resource set to be written (or null if the entity set base type should be used).
/// A running task for the created writer.
/// The write must flush the output when it's finished (inside the last Write call).
- internal override Task CreateODataDeltaWriterAsync(IEdmEntitySetBase entitySet, IEdmEntityType entityType)
+ internal override ValueTask CreateODataDeltaWriterAsync(IEdmEntitySetBase entitySet, IEdmEntityType entityType)
{
this.AssertAsynchronous();
- return TaskUtils.GetTaskForSynchronousOperation((
- thisParam,
- entitySetParam,
- entityTypeParam) => thisParam.CreateODataDeltaWriterImplementation(
- entitySetParam,
- entityTypeParam),
- this,
- entitySet,
- entityType);
+ return ValueTask.FromResult(this.CreateODataDeltaWriterImplementation(entitySet, entityType));
}
///
@@ -719,7 +683,7 @@ internal override void WriteServiceDocument(ODataServiceDocument serviceDocument
/// The service document to write.
/// A task representing the asynchronous operation of writing the service document.
/// It is the responsibility of this method to flush the output before the task finishes.
- internal override async Task WriteServiceDocumentAsync(ODataServiceDocument serviceDocument)
+ internal override async ValueTask WriteServiceDocumentAsync(ODataServiceDocument serviceDocument)
{
this.AssertAsynchronous();
@@ -748,7 +712,7 @@ internal override void WriteEntityReferenceLinks(ODataEntityReferenceLinks links
/// The entity reference links to write as message payload.
/// A task representing the asynchronous writing of the entity reference links.
/// It is the responsibility of this method to flush the output before the task finishes.
- internal override async Task WriteEntityReferenceLinksAsync(ODataEntityReferenceLinks links)
+ internal override async ValueTask WriteEntityReferenceLinksAsync(ODataEntityReferenceLinks links)
{
this.AssertAsynchronous();
@@ -777,7 +741,7 @@ internal override void WriteEntityReferenceLink(ODataEntityReferenceLink link)
/// The link result to write as message payload.
/// A running task representing the writing of the link.
/// It is the responsibility of this method to flush the output before the task finishes.
- internal override async Task WriteEntityReferenceLinkAsync(ODataEntityReferenceLink link)
+ internal override async ValueTask WriteEntityReferenceLinkAsync(ODataEntityReferenceLink link)
{
this.AssertAsynchronous();
@@ -1045,7 +1009,7 @@ private void WriteInStreamErrorImplementation(ODataError error, bool includeDebu
/// be included in the payload. This should only be used in debug scenarios.
///
/// A task that represents the asynchronous write operation.
- private async Task WriteInStreamErrorImplementationAsync(ODataError error, bool includeDebugInformation)
+ private async ValueTask WriteInStreamErrorImplementationAsync(ODataError error, bool includeDebugInformation)
{
if (this.outputInStreamErrorListener != null)
{
@@ -1077,7 +1041,7 @@ private void WritePropertyImplementation(ODataProperty property)
///
/// The property to write.
/// A task that represents the asynchronous write operation.
- private async Task WritePropertyImplementationAsync(ODataProperty property)
+ private async ValueTask WritePropertyImplementationAsync(ODataProperty property)
{
ODataJsonPropertySerializer jsonPropertySerializer = new ODataJsonPropertySerializer(this, /*initContextUriBuilder*/ true);
await jsonPropertySerializer.WriteTopLevelPropertyAsync(property)
@@ -1101,7 +1065,7 @@ private void WriteServiceDocumentImplementation(ODataServiceDocument serviceDocu
///
/// The service document to write.
/// A task that represents the asynchronous write operation.
- private async Task WriteServiceDocumentImplementationAsync(ODataServiceDocument serviceDocument)
+ private async ValueTask WriteServiceDocumentImplementationAsync(ODataServiceDocument serviceDocument)
{
ODataJsonServiceDocumentSerializer jsonServiceDocumentSerializer = new ODataJsonServiceDocumentSerializer(this);
await jsonServiceDocumentSerializer.WriteServiceDocumentAsync(serviceDocument)
@@ -1131,7 +1095,7 @@ private void WriteErrorImplementation(ODataError error, bool includeDebugInforma
/// be included in the payload. This should only be used in debug scenarios.
///
/// A task that represents the asynchronous write operation.
- private async Task WriteErrorImplementationAsync(ODataError error, bool includeDebugInformation)
+ private async ValueTask WriteErrorImplementationAsync(ODataError error, bool includeDebugInformation)
{
ODataJsonSerializer jsonSerializer = new ODataJsonSerializer(this, false);
await jsonSerializer.WriteTopLevelErrorAsync(error, includeDebugInformation)
@@ -1153,7 +1117,7 @@ private void WriteEntityReferenceLinksImplementation(ODataEntityReferenceLinks l
///
/// The entity reference links to write as message payload.
/// A task that represents the asynchronous write operation.
- private async Task WriteEntityReferenceLinksImplementationAsync(ODataEntityReferenceLinks links)
+ private async ValueTask WriteEntityReferenceLinksImplementationAsync(ODataEntityReferenceLinks links)
{
ODataJsonEntityReferenceLinkSerializer jsonEntityReferenceLinkSerializer = new ODataJsonEntityReferenceLinkSerializer(this);
await jsonEntityReferenceLinkSerializer.WriteEntityReferenceLinksAsync(links)
@@ -1175,7 +1139,7 @@ private void WriteEntityReferenceLinkImplementation(ODataEntityReferenceLink lin
///
/// The entity reference link to write as message payload.
/// A task that represents the asynchronous write operation.
- private async Task WriteEntityReferenceLinkImplementationAsync(ODataEntityReferenceLink link)
+ private async ValueTask WriteEntityReferenceLinkImplementationAsync(ODataEntityReferenceLink link)
{
ODataJsonEntityReferenceLinkSerializer jsonEntityReferenceLinkSerializer = new ODataJsonEntityReferenceLinkSerializer(this);
await jsonEntityReferenceLinkSerializer.WriteEntityReferenceLinkAsync(link)
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonParameterReader.cs b/src/Microsoft.OData.Core/Json/ODataJsonParameterReader.cs
index 46299b9a41..0c04e155aa 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonParameterReader.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonParameterReader.cs
@@ -159,11 +159,11 @@ protected override ODataReader CreateResourceReader(IEdmStructuredType expectedR
///
/// Expected entity type to read.
/// An to read the resource value of type .
- protected override Task CreateResourceReaderAsync(IEdmStructuredType expectedResourceType)
+ protected override ValueTask CreateResourceReaderAsync(IEdmStructuredType expectedResourceType)
{
Debug.Assert(expectedResourceType != null, "expectedResourceType != null");
- return Task.FromResult(
+ return ValueTask.FromResult(
new ODataJsonReader(
this.jsonInputContext,
navigationSource: null,
@@ -189,11 +189,11 @@ protected override ODataReader CreateResourceSetReader(IEdmStructuredType expect
///
/// Expected resource set element type to read.
/// An to read the resource set value of type .
- protected override Task CreateResourceSetReaderAsync(IEdmStructuredType expectedResourceType)
+ protected override ValueTask CreateResourceSetReaderAsync(IEdmStructuredType expectedResourceType)
{
Debug.Assert(expectedResourceType != null, "expectedResourceType != null");
- return Task.FromResult(
+ return ValueTask.FromResult(
new ODataJsonReader(
this.jsonInputContext,
navigationSource: null,
@@ -229,12 +229,12 @@ protected override ODataCollectionReader CreateCollectionReader(IEdmTypeReferenc
/// Post-Condition: Any: the reader should be on the start array node of the collection value; if it is not we let the collection reader fail.
/// NOTE: this method does not move the reader.
///
- protected override Task CreateCollectionReaderAsync(IEdmTypeReference expectedItemTypeReference)
+ protected override ValueTask CreateCollectionReaderAsync(IEdmTypeReference expectedItemTypeReference)
{
Debug.Assert(this.jsonInputContext.Model.IsUserModel(), "Should have verified that we created the parameter reader with a user model.");
Debug.Assert(expectedItemTypeReference != null, "expectedItemTypeReference != null");
- return Task.FromResult(
+ return ValueTask.FromResult(
new ODataJsonCollectionReader(this.jsonInputContext, expectedItemTypeReference, listener: this));
}
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonParameterWriter.cs b/src/Microsoft.OData.Core/Json/ODataJsonParameterWriter.cs
index b15451b001..d29c692aca 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonParameterWriter.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonParameterWriter.cs
@@ -159,7 +159,7 @@ protected override ODataWriter CreateFormatResourceSetWriter(string parameterNam
/// Asynchronously start writing an OData payload.
///
/// A task that represents the asynchronous write operation.
- protected override async Task StartPayloadAsync()
+ protected override async ValueTask StartPayloadAsync()
{
// NOTE: we are always writing a request payload here.
await this.jsonValueSerializer.WritePayloadStartAsync()
@@ -172,7 +172,7 @@ await this.jsonOutputContext.JsonWriter.StartObjectScopeAsync()
/// Asynchronously finish writing an OData payload.
///
/// A task that represents the asynchronous write operation.
- protected override async Task EndPayloadAsync()
+ protected override async ValueTask EndPayloadAsync()
{
// NOTE: we are always writing a request payload here.
this.jsonValueSerializer.ReturnDuplicatePropertyNameChecker(this.DuplicatePropertyNameChecker);
@@ -189,7 +189,7 @@ await this.jsonValueSerializer.WritePayloadEndAsync()
/// The value of the parameter to write.
/// The expected type reference of the parameter value.
/// A task that represents the asynchronous write operation.
- protected override async Task WriteValueParameterAsync(string parameterName, object parameterValue, IEdmTypeReference expectedTypeReference)
+ protected override async ValueTask WriteValueParameterAsync(string parameterName, object parameterValue, IEdmTypeReference expectedTypeReference)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
@@ -226,7 +226,7 @@ await this.jsonValueSerializer.WritePrimitiveValueAsync(parameterValue, expected
/// The type reference of the expected item type or null if no expected item type exists.
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains the newly created .
- protected override async Task CreateFormatCollectionWriterAsync(string parameterName, IEdmTypeReference expectedItemType)
+ protected override async ValueTask CreateFormatCollectionWriterAsync(string parameterName, IEdmTypeReference expectedItemType)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
@@ -242,7 +242,7 @@ await this.jsonOutputContext.JsonWriter.WriteNameAsync(parameterName)
/// The type reference of the expected item type or null if no expected item type exists.
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains the newly created .
- protected async override Task CreateFormatResourceWriterAsync(string parameterName, IEdmTypeReference expectedItemType)
+ protected async override ValueTask CreateFormatResourceWriterAsync(string parameterName, IEdmTypeReference expectedItemType)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
@@ -258,7 +258,7 @@ await this.jsonOutputContext.JsonWriter.WriteNameAsync(parameterName)
/// The type reference of the expected item type or null if no expected item type exists.
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains the newly created .
- protected override async Task CreateFormatResourceSetWriterAsync(string parameterName, IEdmTypeReference expectedItemType)
+ protected override async ValueTask CreateFormatResourceSetWriterAsync(string parameterName, IEdmTypeReference expectedItemType)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonPayloadKindDetectionDeserializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonPayloadKindDetectionDeserializer.cs
index 57e092f352..0a584c5ff1 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonPayloadKindDetectionDeserializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonPayloadKindDetectionDeserializer.cs
@@ -67,7 +67,7 @@ internal IEnumerable DetectPayloadKind(ODataPayloadKindDetecti
///
/// Additional information available for the payload kind detection.
/// A task which returns an enumerable of zero, one or more payload kinds that were detected from looking at the payload in the message stream.
- internal async Task> DetectPayloadKindAsync(ODataPayloadKindDetectionInfo detectionInfo)
+ internal async ValueTask> DetectPayloadKindAsync(ODataPayloadKindDetectionInfo detectionInfo)
{
Debug.Assert(detectionInfo != null, "detectionInfo != null");
Debug.Assert(this.ReadingResponse, "Payload kind detection is only supported in responses.");
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonPropertyAndValueDeserializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonPropertyAndValueDeserializer.cs
index 01291086c7..9f3454588f 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonPropertyAndValueDeserializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonPropertyAndValueDeserializer.cs
@@ -76,7 +76,7 @@ internal ODataProperty ReadTopLevelProperty(IEdmTypeReference expectedPropertyTy
///
/// The expected type reference of the property to read.
/// A task which returns an representing the read property.
- internal async Task ReadTopLevelPropertyAsync(IEdmTypeReference expectedPropertyTypeReference)
+ internal async ValueTask ReadTopLevelPropertyAsync(IEdmTypeReference expectedPropertyTypeReference)
{
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet.");
this.JsonReader.AssertNotBuffering();
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonPropertySerializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonPropertySerializer.cs
index 0ba3720716..ea9957ac20 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonPropertySerializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonPropertySerializer.cs
@@ -350,7 +350,7 @@ await this.WritePropertyAsync(
/// The metadatabuilder for the resource
/// A task that represents the asynchronous write operation.
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Splitting the code would make the logic harder to understand; class coupling is only slightly above threshold.")]
- internal async Task WritePropertyAsync(
+ internal async ValueTask WritePropertyAsync(
ODataProperty property,
IEdmStructuredType owningType,
bool isTopLevel,
@@ -440,14 +440,12 @@ await this.WriteStreamPropertyAsync(streamValue, isOpenPropertyType)
return;
}
-#if NETCOREAPP
if (value is ODataJsonElementValue jsonElementValue)
{
await this.WriteJsonElementPropertyAsync(jsonElementValue)
.ConfigureAwait(false);
return;
}
-#endif
}
@@ -460,7 +458,7 @@ await this.WriteJsonElementPropertyAsync(jsonElementValue)
/// The DuplicatePropertyNameChecker to use.
/// The metadatabuilder for the resource
/// A task that represents the asynchronous write operation.
- internal async Task WritePropertyInfoAsync(
+ internal async ValueTask WritePropertyInfoAsync(
ODataPropertyInfo propertyInfo,
IEdmStructuredType owningType,
bool isTopLevel,
@@ -936,7 +934,7 @@ await this.jsonValueSerializer.WriteUntypedValueAsync(untypedValue)
/// Asynchronously writes an value.
///
/// The value to be written.
- private async Task WriteJsonElementPropertyAsync(ODataJsonElementValue jsonElementvalue)
+ private async ValueTask WriteJsonElementPropertyAsync(ODataJsonElementValue jsonElementvalue)
{
await this.JsonWriter.WriteNameAsync(this.currentPropertyInfo.WireName)
.ConfigureAwait(false);
@@ -953,7 +951,7 @@ await this.JsonWriter.WriteValueAsync(jsonElementvalue.Value)
/// The property name.
/// The metadata builder for the resource.
/// A task that represents the asynchronous write operation.
- private async Task WriteStreamValueAsync(
+ private async ValueTask WriteStreamValueAsync(
IODataStreamReferenceInfo streamInfo,
string propertyName,
ODataResourceMetadataBuilder metadataBuilder)
@@ -974,7 +972,7 @@ await this.WriteStreamInfoAsync(propertyName, streamInfo)
/// If writing top level property.
/// If writing an undeclared property.
/// A task that represents the asynchronous write operation.
- private Task WriteInstanceAnnotationAsync(ODataPropertyInfo property, bool isTopLevel, bool isUndeclaredProperty)
+ private ValueTask WriteInstanceAnnotationAsync(ODataPropertyInfo property, bool isTopLevel, bool isUndeclaredProperty)
{
if (property.InstanceAnnotations.Count != 0)
{
@@ -988,7 +986,7 @@ private Task WriteInstanceAnnotationAsync(ODataPropertyInfo property, bool isTop
}
}
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -997,7 +995,7 @@ private Task WriteInstanceAnnotationAsync(ODataPropertyInfo property, bool isTop
/// The property to handle.
/// If writing top level property.
/// A task that represents the asynchronous write operation.
- private Task WriteODataTypeAnnotationAsync(ODataPropertyInfo property, bool isTopLevel)
+ private ValueTask WriteODataTypeAnnotationAsync(ODataPropertyInfo property, bool isTopLevel)
{
if (property.TypeAnnotation != null && property.TypeAnnotation.TypeName != null)
{
@@ -1020,7 +1018,7 @@ private Task WriteODataTypeAnnotationAsync(ODataPropertyInfo property, bool isTo
}
}
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -1029,7 +1027,7 @@ private Task WriteODataTypeAnnotationAsync(ODataPropertyInfo property, bool isTo
/// The name of the stream property to write.
/// The stream reference value to be written
/// A task that represents the asynchronous write operation.
- private async Task WriteStreamInfoAsync(string propertyName, IODataStreamReferenceInfo streamInfo)
+ private async ValueTask WriteStreamInfoAsync(string propertyName, IODataStreamReferenceInfo streamInfo)
{
Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)");
Debug.Assert(streamInfo != null, "streamReferenceValue != null");
@@ -1076,7 +1074,7 @@ await this.JsonWriter.WriteValueAsync(mediaETag)
///
/// The property to write out.
/// A task that represents the asynchronous write operation.
- private async Task WriteNullPropertyAsync(
+ private async ValueTask WriteNullPropertyAsync(
ODataPropertyInfo property)
{
this.WriterValidator.ValidateNullPropertyValue(
@@ -1120,7 +1118,7 @@ await this.JsonValueSerializer.WriteNullValueAsync()
/// The resource value to be written
/// If the property is open.
/// A task that represents the asynchronous write operation.
- private async Task WriteResourcePropertyAsync(
+ private async ValueTask WriteResourcePropertyAsync(
ODataProperty property,
ODataResourceValue resourceValue,
bool isOpenPropertyType)
@@ -1146,7 +1144,7 @@ await this.JsonValueSerializer.WriteResourceValueAsync(
/// The enum value to be written.
/// If the property is open.
/// A task that represents the asynchronous write operation.
- private async Task WriteEnumPropertyAsync(
+ private async ValueTask WriteEnumPropertyAsync(
ODataEnumValue enumValue,
bool isOpenPropertyType)
{
@@ -1165,7 +1163,7 @@ await this.JsonValueSerializer.WriteEnumValueAsync(enumValue, this.currentProper
/// The collection value to be written
/// If the property is open.
/// A task that represents the asynchronous write operation.
- private async Task WriteCollectionPropertyAsync(
+ private async ValueTask WriteCollectionPropertyAsync(
ODataCollectionValue collectionValue,
bool isOpenPropertyType)
{
@@ -1192,7 +1190,7 @@ await this.JsonValueSerializer.WriteCollectionValueAsync(
/// The stream value to be written
/// If the property is open.
/// A task that represents the asynchronous write operation.
- private async Task WriteStreamPropertyAsync(ODataBinaryStreamValue streamValue, bool isOpenPropertyType)
+ private async ValueTask WriteStreamPropertyAsync(ODataBinaryStreamValue streamValue, bool isOpenPropertyType)
{
await this.JsonWriter.WriteNameAsync(this.currentPropertyInfo.WireName)
.ConfigureAwait(false);
@@ -1206,7 +1204,7 @@ await this.JsonValueSerializer.WriteStreamValueAsync(streamValue)
/// The primitive value to be written
/// If the property is open.
/// A task that represents the asynchronous write operation.
- private async Task WritePrimitivePropertyAsync(
+ private async ValueTask WritePrimitivePropertyAsync(
ODataPrimitiveValue primitiveValue,
bool isOpenPropertyType)
{
@@ -1225,7 +1223,7 @@ await this.JsonValueSerializer.WritePrimitiveValueAsync(primitiveValue.Value, th
/// Asynchronously writes the type name on the wire.
///
/// A task that represents the asynchronous write operation.
- private Task WritePropertyTypeNameAsync()
+ private ValueTask WritePropertyTypeNameAsync()
{
string typeNameToWrite = this.currentPropertyInfo.TypeNameToWrite;
if (typeNameToWrite != null)
@@ -1241,7 +1239,7 @@ private Task WritePropertyTypeNameAsync()
}
}
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
}
}
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonReader.cs b/src/Microsoft.OData.Core/Json/ODataJsonReader.cs
index 8094c7f7c7..c7e56fd4c2 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonReader.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonReader.cs
@@ -191,7 +191,7 @@ protected override bool ReadAtStartImplementation()
/// when reading a resource: the first node of the first nested resource info value, null for a null expanded link or an end object
/// node if there are no navigation links.
///
- protected override async Task ReadAtStartImplementationAsync()
+ protected override async ValueTask ReadAtStartImplementationAsync()
{
Debug.Assert(this.State == ODataReaderState.Start, "this.State == ODataReaderState.Start");
Debug.Assert(
@@ -247,7 +247,7 @@ protected override bool ReadAtResourceSetStartImplementation()
/// Post-Condition: The reader is positioned over the StartObject node of the first resource in the resource set or
/// on the node following the resource set end in case of an empty resource set
///
- protected override Task ReadAtResourceSetStartImplementationAsync()
+ protected override ValueTask ReadAtResourceSetStartImplementationAsync()
{
return this.ReadAtResourceSetStartInternalImplementationAsync();
}
@@ -283,7 +283,7 @@ protected override bool ReadAtResourceSetEndImplementation()
/// JsonNodeType.EndArray end of expanded link in request, in this case the resource set doesn't actually own the array object and it won't read it.
/// Any in case of expanded resource set in request, this might be the next item in the expanded array, which is not a resource
///
- protected override Task ReadAtResourceSetEndImplementationAsync()
+ protected override ValueTask ReadAtResourceSetEndImplementationAsync()
{
return this.ReadAtResourceSetEndInternalImplementationAsync();
}
@@ -328,9 +328,9 @@ protected override bool ReadAtResourceStartImplementation()
/// JsonNodeType.Property The next property after a deferred link or entity reference link
/// JsonNodeType.EndObject If no (more) properties exist in the resource's content
///
- protected override Task ReadAtResourceStartImplementationAsync()
+ protected override ValueTask ReadAtResourceStartImplementationAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(this.ReadAtResourceStartImplementation);
+ return ValueTask.FromResult(this.ReadAtResourceStartImplementation());
}
///
@@ -356,7 +356,7 @@ protected override bool ReadAtResourceEndImplementation()
/// JsonNodeType.PrimitiveValue (null) end of null expanded resource
/// Post-Condition: The reader is positioned on the first node after the resource's end-object node
///
- protected override Task ReadAtResourceEndImplementationAsync()
+ protected override ValueTask ReadAtResourceEndImplementationAsync()
{
return this.ReadAtResourceEndInternalImplementationAsync();
}
@@ -385,7 +385,7 @@ protected override bool ReadAtPrimitiveImplementation()
/// Pre-Condition: JsonNodeType.PrimitiveValue end of primitive value in a collection
/// Post-Condition: The reader is positioned on the first node after the primitive value
///
- protected override async Task ReadAtPrimitiveImplementationAsync()
+ protected override async ValueTask ReadAtPrimitiveImplementationAsync()
{
Debug.Assert(
this.jsonResourceDeserializer.JsonReader.NodeType == JsonNodeType.PrimitiveValue,
@@ -433,7 +433,7 @@ protected override bool ReadAtStreamImplementation()
/// Implementation of the reader logic when in state 'Stream'.
///
/// A task which returns true if more items can be read from the reader; otherwise false.
- protected override async Task ReadAtStreamImplementationAsync()
+ protected override async ValueTask ReadAtStreamImplementationAsync()
{
this.PopScope(ODataReaderState.Stream);
@@ -478,7 +478,7 @@ protected override TextReader CreateTextReaderImplementation()
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains a for reading the stream property.
///
- protected override Task CreateReadStreamImplementationAsync()
+ protected override ValueTask CreateReadStreamImplementationAsync()
{
return this.jsonInputContext.JsonReader.CreateReadStreamAsync();
}
@@ -490,7 +490,7 @@ protected override Task CreateReadStreamImplementationAsync()
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains a for reading the string property.
///
- protected override Task CreateTextReaderImplementationAsync()
+ protected override ValueTask CreateTextReaderImplementationAsync()
{
return this.jsonInputContext.JsonReader.CreateTextReaderAsync();
}
@@ -535,7 +535,7 @@ protected override bool ReadAtNestedResourceInfoStartImplementation()
/// JsonNodeType.Property deferred link with more properties in owning resource
/// JsonNodeType.EndObject deferred link as last property of the owning resource
///
- protected override Task ReadAtNestedResourceInfoStartImplementationAsync()
+ protected override ValueTask ReadAtNestedResourceInfoStartImplementationAsync()
{
return this.ReadAtNestedResourceInfoStartInternalImplementationAsync();
}
@@ -571,12 +571,11 @@ protected override bool ReadAtNestedResourceInfoEndImplementation()
/// JsonNoteType.Property property after deferred link or entity reference link
/// JsonNodeType.EndObject end of the parent resource
///
- protected override async Task ReadAtNestedResourceInfoEndImplementationAsync()
+ protected override ValueTask ReadAtNestedResourceInfoEndImplementationAsync()
{
this.PopScope(ODataReaderState.NestedResourceInfoEnd);
- return await this.ReadNextNestedInfoAsync()
- .ConfigureAwait(false);
+ return this.ReadNextNestedInfoAsync();
}
#endregion NestedResourceInfo
@@ -613,7 +612,7 @@ protected override bool ReadAtEntityReferenceLink()
/// JsonNodeType.Property: there are more properties after the expanded link property in the owning resource
/// Any: expanded collection link - the node after the entity reference link.
///
- protected override async Task ReadAtEntityReferenceLinkAsync()
+ protected override async ValueTask ReadAtEntityReferenceLinkAsync()
{
this.PopScope(ODataReaderState.EntityReferenceLink);
Debug.Assert(this.State == ODataReaderState.NestedResourceInfoStart,
@@ -654,7 +653,7 @@ protected override bool ReadAtDeltaResourceSetStartImplementation()
/// Post-Condition: The reader is positioned over the StartObject node of the first resource in the resource set or
/// on the node following the resource set end in case of an empty resource set
///
- protected override Task ReadAtDeltaResourceSetStartImplementationAsync()
+ protected override ValueTask ReadAtDeltaResourceSetStartImplementationAsync()
{
return this.ReadAtResourceSetStartInternalImplementationAsync();
}
@@ -691,7 +690,7 @@ protected override bool ReadAtDeltaResourceSetEndImplementation()
/// JsonNodeType.EndArray end of expanded link in request, in this case the resource set doesn't actually own the array object and it won't read it.
/// Any in case of expanded resource set in request, this might be the next item in the expanded array, which is not a resource
///
- protected override Task ReadAtDeltaResourceSetEndImplementationAsync()
+ protected override ValueTask ReadAtDeltaResourceSetEndImplementationAsync()
{
// Logic is same as for ResourceSet
return this.ReadAtResourceSetEndInternalImplementationAsync();
@@ -746,7 +745,7 @@ protected override bool ReadAtDeletedResourceEndImplementation()
/// JsonNodeType.PrimitiveValue (null) end of null expanded resource
/// Post-Condition: The reader is positioned on the first node after the deleted resource's end-object node
///
- protected override Task ReadAtDeletedResourceEndImplementationAsync()
+ protected override ValueTask ReadAtDeletedResourceEndImplementationAsync()
{
// Same logic as ReadAtResourceEndImplementationAsync
return this.ReadAtResourceEndInternalImplementationAsync();
@@ -783,7 +782,7 @@ protected override bool ReadAtDeltaLinkImplementation()
/// JsonNodeType.Property The next property after a deferred link or entity reference link
/// JsonNodeType.EndObject If no (more) properties exist in the resource's content
///
- protected override Task ReadAtDeltaLinkImplementationAsync()
+ protected override ValueTask ReadAtDeltaLinkImplementationAsync()
{
return this.EndDeltaLinkAsync(ODataReaderState.DeltaLink);
}
@@ -819,7 +818,7 @@ protected override bool ReadAtDeltaDeletedLinkImplementation()
/// JsonNodeType.Property The next property after a deferred link or entity reference link
/// JsonNodeType.EndObject If no (more) properties exist in the resource's content
///
- protected override Task ReadAtDeltaDeletedLinkImplementationAsync()
+ protected override ValueTask ReadAtDeltaDeletedLinkImplementationAsync()
{
return this.EndDeltaLinkAsync(ODataReaderState.DeltaDeletedLink);
}
@@ -2726,7 +2725,7 @@ await this.ReadResourceSetItemStartAsync(propertyAndAnnotationCollector, selecte
/// Post-Condition: The reader is positioned over the StartObject node of the first resource in the resource set or
/// on the node following the resource set end in case of an empty resource set
///
- private async Task ReadAtResourceSetStartInternalImplementationAsync()
+ private async ValueTask ReadAtResourceSetStartInternalImplementationAsync()
{
await this.ReadNextResourceSetItemAsync()
.ConfigureAwait(false);
@@ -2755,7 +2754,7 @@ await this.ReadNextResourceSetItemAsync()
/// JsonNodeType.EndArray end of expanded link in request, in this case the resource set doesn't actually own the array object and it won't read it.
/// Any in case of expanded resource set in request, this might be the next item in the expanded array, which is not a resource
///
- private async Task ReadAtResourceSetEndInternalImplementationAsync()
+ private async ValueTask ReadAtResourceSetEndInternalImplementationAsync()
{
Debug.Assert(this.State == ODataReaderState.ResourceSetEnd || this.State == ODataReaderState.DeltaResourceSetEnd, "Not in (delta) resource set end state.");
Debug.Assert(
@@ -2857,7 +2856,7 @@ await this.ReadNextResourceSetItemAsync()
/// JsonNodeType.PrimitiveValue (null) end of null expanded resource
/// Post-Condition: The reader is positioned on the first node after the resource's end-object node
///
- private async Task ReadAtResourceEndInternalImplementationAsync()
+ private async ValueTask ReadAtResourceEndInternalImplementationAsync()
{
Debug.Assert(
this.jsonResourceDeserializer.JsonReader.NodeType == JsonNodeType.EndObject ||
@@ -2940,7 +2939,7 @@ await this.ReadNextResourceSetItemAsync()
/// JsonNodeType.EndObject deferred link as last property of the owning resource or
/// reporting projected navigation links missing in the payload
///
- private async Task ReadAtNestedResourceInfoStartInternalImplementationAsync()
+ private async ValueTask ReadAtNestedResourceInfoStartInternalImplementationAsync()
{
Debug.Assert(
this.jsonResourceDeserializer.JsonReader.NodeType == JsonNodeType.Property ||
@@ -3046,7 +3045,7 @@ await this.ReadNextNestedResourceInfoContentItemInRequestAsync()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains true if more items can be read from the reader; otherwise false.
///
- private async Task ReadNextNestedInfoAsync()
+ private async ValueTask ReadNextNestedInfoAsync()
{
this.jsonResourceDeserializer.AssertJsonCondition(
JsonNodeType.EndObject,
@@ -3086,7 +3085,7 @@ private async Task ReadNextNestedInfoAsync()
/// Asynchronously reads the next item in a nested resource info content in a request payload.
///
/// A task that represents the asynchronous read operation.
- private async Task ReadNextNestedResourceInfoContentItemInRequestAsync()
+ private async ValueTask ReadNextNestedResourceInfoContentItemInRequestAsync()
{
Debug.Assert(
this.CurrentScope.State == ODataReaderState.NestedResourceInfoStart,
@@ -3135,7 +3134,7 @@ await this.ReadExpandedNestedResourceInfoStartAsync(nestedResourceInfo.NestedRes
///
/// The reader state to switch to.
/// A task that represents the asynchronous read operation.
- private async Task StartDeltaLinkAsync(ODataReaderState state)
+ private async ValueTask StartDeltaLinkAsync(ODataReaderState state)
{
Debug.Assert(
state == ODataReaderState.DeltaLink || state == ODataReaderState.DeltaDeletedLink,
@@ -3685,7 +3684,7 @@ await this.jsonResourceDeserializer.ReadResourceTypeNameAsync(this.CurrentResour
/// JsonNodeType.EndObject No more other annotation or property in the link.
/// Post-Condition: The reader is positioned on the first node after the link's end-object node.
///
- private async Task EndDeltaLinkAsync(ODataReaderState readerState)
+ private async ValueTask EndDeltaLinkAsync(ODataReaderState readerState)
{
Debug.Assert(
readerState == ODataReaderState.DeltaLink || readerState == ODataReaderState.DeltaDeletedLink,
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonResourceDeserializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonResourceDeserializer.cs
index 096fb4a573..6df4b4d1fa 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonResourceDeserializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonResourceDeserializer.cs
@@ -3679,15 +3679,17 @@ await this.ReadOverPropertyNameAsync()
///
/// Asynchronously reads over the current property name if positioned on a property
///
- /// A task that represents the asynchronous read operation.
- private Task ReadOverPropertyNameAsync()
+ /// A task that represents the asynchronous read operation.
+ /// The value of the result is true if a property node was found,
+ /// or false if the node is not a property or the end of input was reached.
+ private ValueTask ReadOverPropertyNameAsync()
{
if (this.JsonReader.NodeType == JsonNodeType.Property)
{
return this.JsonReader.ReadAsync();
}
- return TaskUtils.CompletedTask;
+ return ValueTask.FromResult(false);
}
///
@@ -3702,7 +3704,7 @@ private Task ReadOverPropertyNameAsync()
/// Post-Condition: JsonNodeType.Property: the next property of the resource
/// JsonNodeType.EndObject: the end-object node of the resource
///
- private async Task ReadEntryDataPropertyAsync(IODataJsonReaderResourceState resourceState, IEdmProperty edmProperty, string propertyTypeName)
+ private async ValueTask ReadEntryDataPropertyAsync(IODataJsonReaderResourceState resourceState, IEdmProperty edmProperty, string propertyTypeName)
{
Debug.Assert(resourceState != null, "resourceState != null");
Debug.Assert(edmProperty != null, "edmProperty != null");
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonResourceSerializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonResourceSerializer.cs
index 4fd7936eaa..03f2f20cc2 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonResourceSerializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonResourceSerializer.cs
@@ -341,7 +341,7 @@ internal ODataContextUrlInfo WriteResourceSetContextUri(ODataResourceTypeContext
/// The expected resource type name of the items in the resource set.
/// true if the resource set is for an undeclared property
/// A task that represents the asynchronous write operation.
- internal async Task WriteResourceSetStartMetadataPropertiesAsync(
+ internal async ValueTask WriteResourceSetStartMetadataPropertiesAsync(
ODataResourceSet resourceSet,
string propertyName,
string expectedResourceTypeName,
@@ -375,7 +375,7 @@ await this.ODataAnnotationWriter.WriteODataTypePropertyAnnotationAsync(propertyN
///
/// The resource state for which to write the metadata properties.
/// A task that represents the asynchronous write operation.
- internal async Task WriteResourceStartMetadataPropertiesAsync(IODataJsonWriterResourceState resourceState)
+ internal async ValueTask WriteResourceStartMetadataPropertiesAsync(IODataJsonWriterResourceState resourceState)
{
Debug.Assert(resourceState != null, "resourceState != null");
@@ -428,7 +428,7 @@ await this.JsonWriter.WriteValueAsync(etag)
///
/// This method will only write properties which were not written yet.
///
- internal async Task WriteResourceMetadataPropertiesAsync(IODataJsonWriterResourceState resourceState)
+ internal async ValueTask WriteResourceMetadataPropertiesAsync(IODataJsonWriterResourceState resourceState)
{
Debug.Assert(resourceState != null, "resourceState != null");
@@ -511,7 +511,7 @@ await this.JsonWriter.WriteValueAsync(mediaETag)
/// The resource state for which to write the metadata properties.
/// The DuplicatePropertyNameChecker to use.
/// A task that represents the asynchronous write operation.
- internal async Task WriteResourceEndMetadataPropertiesAsync(
+ internal async ValueTask WriteResourceEndMetadataPropertiesAsync(
IODataJsonWriterResourceState resourceState,
IDuplicatePropertyNameChecker duplicatePropertyNameChecker)
{
@@ -567,7 +567,7 @@ await this.WriteOperationsAsync(functions.Cast(), /*isAction*/ f
/// The navigation link to write the metadata for.
/// The DuplicatePropertyNameChecker to use.
/// A task that represents the asynchronous write operation.
- internal async Task WriteNavigationLinkMetadataAsync(ODataNestedResourceInfo nestedResourceInfo, IDuplicatePropertyNameChecker duplicatePropertyNameChecker)
+ internal async ValueTask WriteNavigationLinkMetadataAsync(ODataNestedResourceInfo nestedResourceInfo, IDuplicatePropertyNameChecker duplicatePropertyNameChecker)
{
Debug.Assert(nestedResourceInfo != null, "nestedResourceInfo != null");
Debug.Assert(!string.IsNullOrEmpty(nestedResourceInfo.Name), "The nested resource info Name should have been validated by now.");
@@ -599,7 +599,7 @@ await this.JsonWriter.WriteValueAsync(this.UriToString(navigationLinkUrl))
/// The navigation link to write the metadata for.
/// The contextUrl information for current element.
/// A task that represents the asynchronous write operation.
- internal Task WriteNestedResourceInfoContextUrlAsync(ODataNestedResourceInfo nestedResourceInfo, ODataContextUrlInfo contextUrlInfo)
+ internal ValueTask WriteNestedResourceInfoContextUrlAsync(ODataNestedResourceInfo nestedResourceInfo, ODataContextUrlInfo contextUrlInfo)
{
return this.WriteContextUriPropertyAsync(
ODataPayloadKind.Resource,
@@ -643,7 +643,7 @@ await this.WriteOperationMetadataGroupAsync(metadataGroup)
/// The parent contextUrlInfo.
/// A task that represents the asynchronous write operation.
/// The value of the TResult parameter contains the created context uri info.
- internal Task WriteDeltaContextUriAsync(ODataResourceTypeContext typeContext, ODataDeltaKind kind, ODataContextUrlInfo parentContextUrlInfo = null)
+ internal ValueTask WriteDeltaContextUriAsync(ODataResourceTypeContext typeContext, ODataDeltaKind kind, ODataContextUrlInfo parentContextUrlInfo = null)
{
ODataUri odataUri = this.JsonOutputContext.MessageWriterSettings.ODataUri;
@@ -668,7 +668,7 @@ internal Task WriteDeltaContextUriAsync(ODataResourceTypeCo
/// The parent contextUrlInfo.
/// A task that represents the asynchronous write operation.
/// The value of the TResult parameter contains the created context uri info.
- internal Task WriteResourceContextUriAsync(ODataResourceTypeContext typeContext, ODataContextUrlInfo parentContextUrlInfo = null)
+ internal ValueTask WriteResourceContextUriAsync(ODataResourceTypeContext typeContext, ODataContextUrlInfo parentContextUrlInfo = null)
{
ODataUri odataUri = this.JsonOutputContext.MessageWriterSettings.ODataUri;
@@ -691,7 +691,7 @@ internal Task WriteResourceContextUriAsync(ODataResourceTyp
/// The context object to answer basic questions regarding the type of the resource set.
/// A task that represents the asynchronous write operation.
/// The value of the TResult parameter contains the created context uri info.
- internal Task WriteResourceSetContextUriAsync(ODataResourceTypeContext typeContext)
+ internal ValueTask WriteResourceSetContextUriAsync(ODataResourceTypeContext typeContext)
{
ODataUri odataUri = this.JsonOutputContext.MessageWriterSettings.ODataUri;
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonSerializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonSerializer.cs
index 14596c3c4b..a477c84012 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonSerializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonSerializer.cs
@@ -222,16 +222,16 @@ internal void WriteTopLevelError(ODataError error, bool includeDebugInformation)
/// Asynchronously writes the start of the entire JSON payload.
///
/// A task that represents the asynchronous write operation.
- internal Task WritePayloadStartAsync()
+ internal ValueTask WritePayloadStartAsync()
{
if (this.MessageWriterSettings.HasJsonPaddingFunction())
{
return WritePayloadStartInnerAsync(this.JsonWriter, this.MessageWriterSettings.JsonPCallback);
}
- return Task.CompletedTask;
+ return ValueTask.CompletedTask;
- async Task WritePayloadStartInnerAsync(IJsonWriter localJsonWriter, string jsonPCallback)
+ async ValueTask WritePayloadStartInnerAsync(IJsonWriter localJsonWriter, string jsonPCallback)
{
await localJsonWriter.WritePaddingFunctionNameAsync(jsonPCallback).ConfigureAwait(false);
await localJsonWriter.StartPaddingFunctionScopeAsync().ConfigureAwait(false);
@@ -242,14 +242,14 @@ async Task WritePayloadStartInnerAsync(IJsonWriter localJsonWriter, string jsonP
/// Asynchronously writes the end of the entire JSON payload.
///
/// A task that represents the asynchronous write operation.
- internal Task WritePayloadEndAsync()
+ internal ValueTask WritePayloadEndAsync()
{
if (this.MessageWriterSettings.HasJsonPaddingFunction())
{
return this.JsonWriter.EndPaddingFunctionScopeAsync();
}
- return Task.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -262,7 +262,7 @@ internal Task WritePayloadEndAsync()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the contextUrlInfo,
/// if the context URI was successfully written.
- internal async Task WriteContextUriPropertyAsync(
+ internal ValueTask WriteContextUriPropertyAsync(
ODataPayloadKind payloadKind,
Func contextUrlInfoGen = null,
ODataContextUrlInfo parentContextUrlInfo = null,
@@ -270,7 +270,7 @@ internal async Task WriteContextUriPropertyAsync(
{
if (IsJsonNoMetadataLevel())
{
- return null;
+ return ValueTask.FromResult(null);
}
ODataContextUrlInfo contextUrlInfo = null;
@@ -280,11 +280,11 @@ internal async Task WriteContextUriPropertyAsync(
contextUrlInfo = contextUrlInfoGen();
}
- return await WriteContextUriPropertyImplementationAsync(
+ return WriteContextUriPropertyImplementationAsync(
payloadKind,
parentContextUrlInfo,
contextUrlInfo,
- propertyName).ConfigureAwait(false);
+ propertyName);
}
///
@@ -292,7 +292,7 @@ internal async Task WriteContextUriPropertyAsync(
///
/// The delegate that writes the actual JSON payload that is being wrapped.
/// A task that represents the asynchronous write operation.
- internal async Task WriteTopLevelPayloadAsync(Func payloadWriterFunc)
+ internal async ValueTask WriteTopLevelPayloadAsync(Func payloadWriterFunc)
{
Debug.Assert(payloadWriterFunc != null, "payloadWriterAction != null");
@@ -309,7 +309,7 @@ internal async Task WriteTopLevelPayloadAsync(Func payloadWriterFunc)
/// The error instance to write.
/// A flag indicating whether error details should be written (in debug mode only) or not.
/// A task that represents the asynchronous write operation.
- internal Task WriteTopLevelErrorAsync(ODataError error, bool includeDebugInformation)
+ internal ValueTask WriteTopLevelErrorAsync(ODataError error, bool includeDebugInformation)
{
Debug.Assert(error != null, "error != null");
@@ -385,7 +385,7 @@ internal string UriToString(Uri uri)
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the instance
/// if the context URI was successfully written.
- protected async Task WriteContextUriPropertyAsync(
+ protected ValueTask WriteContextUriPropertyAsync(
ODataPayloadKind payloadKind,
Func contextUrlInfoGen,
TArg arg,
@@ -394,7 +394,7 @@ protected async Task WriteContextUriPropertyAsync(
{
if (IsJsonNoMetadataLevel())
{
- return null;
+ return ValueTask.FromResult(null);
}
ODataContextUrlInfo contextUrlInfo = null;
@@ -404,11 +404,11 @@ protected async Task WriteContextUriPropertyAsync(
contextUrlInfo = contextUrlInfoGen(arg);
}
- return await WriteContextUriPropertyImplementationAsync(
+ return WriteContextUriPropertyImplementationAsync(
payloadKind,
parentContextUrlInfo,
contextUrlInfo,
- propertyName).ConfigureAwait(false);
+ propertyName);
}
///
@@ -425,7 +425,7 @@ protected async Task WriteContextUriPropertyAsync(
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the instance
/// if the context URI was successfully written.
- protected async Task WriteContextUriPropertyAsync(
+ protected ValueTask WriteContextUriPropertyAsync(
ODataPayloadKind payloadKind,
Func contextUrlInfoGen,
TArg1 arg1,
@@ -435,7 +435,7 @@ protected async Task WriteContextUriPropertyAsync(null);
}
ODataContextUrlInfo contextUrlInfo = null;
@@ -445,11 +445,11 @@ protected async Task WriteContextUriPropertyAsync
@@ -468,7 +468,7 @@ protected async Task WriteContextUriPropertyAsyncA task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the instance
/// if the context URI was successfully written.
- protected async Task WriteContextUriPropertyAsync(
+ protected ValueTask WriteContextUriPropertyAsync(
ODataPayloadKind payloadKind,
Func contextUrlInfoGen,
TArg1 arg1,
@@ -479,7 +479,7 @@ protected async Task WriteContextUriPropertyAsync(null);
}
ODataContextUrlInfo contextUrlInfo = null;
@@ -489,11 +489,11 @@ protected async Task WriteContextUriPropertyAsync
@@ -514,7 +514,7 @@ protected async Task WriteContextUriPropertyAsyncA task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the instance
/// if the context URI was successfully written.
- protected async Task WriteContextUriPropertyAsync(
+ protected ValueTask WriteContextUriPropertyAsync(
ODataPayloadKind payloadKind,
Func contextUrlInfoGen,
TArg1 arg1,
@@ -526,7 +526,7 @@ protected async Task WriteContextUriPropertyAsync(null);
}
ODataContextUrlInfo contextUrlInfo = null;
@@ -536,11 +536,11 @@ protected async Task WriteContextUriPropertyAsync
@@ -597,8 +597,8 @@ protected async Task WriteTopLevelPayloadAsync(
/// The second argument value provided to the delegate.
/// The third argument value provided to the delegate.
/// A task that represents the asynchronous write operation.
- protected async Task WriteTopLevelPayloadAsync(
- Func payloadWriterFunc,
+ protected async ValueTask WriteTopLevelPayloadAsync(
+ Func payloadWriterFunc,
TArg1 arg1,
TArg2 arg2,
TArg3 arg3)
@@ -633,7 +633,7 @@ private bool IsJsonNoMetadataLevel()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the instance
/// if the context URI was successfully written.
- private async Task WriteContextUriPropertyImplementationAsync(
+ private async ValueTask WriteContextUriPropertyImplementationAsync(
ODataPayloadKind payloadKind,
ODataContextUrlInfo parentContextUrlInfo,
ODataContextUrlInfo contextUrlInfo,
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonServiceDocumentDeserializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonServiceDocumentDeserializer.cs
index fbb8f009f2..72f65defed 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonServiceDocumentDeserializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonServiceDocumentDeserializer.cs
@@ -74,7 +74,7 @@ internal ODataServiceDocument ReadServiceDocument()
/// Pre-Condition: JsonNodeType.None: assumes that the JSON reader has not been used yet.
/// Post-Condition: JsonNodeType.EndOfInput
///
- internal async Task ReadServiceDocumentAsync()
+ internal async ValueTask ReadServiceDocumentAsync()
{
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet.");
this.JsonReader.AssertNotBuffering();
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonValueSerializer.cs b/src/Microsoft.OData.Core/Json/ODataJsonValueSerializer.cs
index af5c48c145..fa30cb4f7a 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonValueSerializer.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonValueSerializer.cs
@@ -400,7 +400,7 @@ public virtual void WriteStreamValue(ODataBinaryStreamValue streamValue)
/// Asynchronously writes a null value to the writer.
///
/// A task that represents the asynchronous write operation.
- public virtual Task WriteNullValueAsync()
+ public virtual ValueTask WriteNullValueAsync()
{
return this.JsonWriter.WriteValueAsync((string)null);
}
@@ -411,7 +411,7 @@ public virtual Task WriteNullValueAsync()
/// enum value
/// expected type reference
/// A task that represents the asynchronous write operation.
- public virtual Task WriteEnumValueAsync(
+ public virtual ValueTask WriteEnumValueAsync(
ODataEnumValue value,
IEdmTypeReference expectedTypeReference)
{
@@ -711,7 +711,7 @@ await TaskUtils.GetTaskForSynchronousOperation(
///
/// The untyped value to write.
/// A task that represents the asynchronous write operation.
- public virtual Task WriteUntypedValueAsync(
+ public virtual ValueTask WriteUntypedValueAsync(
ODataUntypedValue value)
{
Debug.Assert(value != null, "value != null");
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonWriter.cs b/src/Microsoft.OData.Core/Json/ODataJsonWriter.cs
index 56c8fe2f11..fefdefce21 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonWriter.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonWriter.cs
@@ -1255,7 +1255,7 @@ protected override NestedResourceInfoScope CreateNestedResourceInfoScope(WriterS
/// Asynchronously starts writing a payload (called exactly once before anything else)
///
/// A task that represents the asynchronous write operation.
- protected override Task StartPayloadAsync()
+ protected override ValueTask StartPayloadAsync()
{
return this.jsonResourceSerializer.WritePayloadStartAsync();
}
@@ -1264,7 +1264,7 @@ protected override Task StartPayloadAsync()
/// Asynchronously ends writing a payload (called exactly once after everything else in case of success)
///
/// A task that represents the asynchronous write operation.
- protected override Task EndPayloadAsync()
+ protected override ValueTask EndPayloadAsync()
{
return this.jsonResourceSerializer.WritePayloadEndAsync();
}
@@ -1274,7 +1274,7 @@ protected override Task EndPayloadAsync()
///
/// The resource to write.
/// A task that represents the asynchronous write operation.
- protected override async Task StartResourceAsync(ODataResource resource)
+ protected override async ValueTask StartResourceAsync(ODataResource resource)
{
ODataNestedResourceInfo parentNavLink = this.ParentNestedResourceInfo;
if (parentNavLink != null)
@@ -1372,7 +1372,7 @@ await this.jsonResourceSerializer.WritePropertiesAsync(
///
/// The resource to write.
/// A task that represents the asynchronous write operation.
- protected override async Task EndResourceAsync(ODataResource resource)
+ protected override async ValueTask EndResourceAsync(ODataResource resource)
{
if (resource == null)
{
@@ -1407,7 +1407,7 @@ await this.jsonWriter.EndObjectScopeAsync()
///
/// The property info to write.
/// A task that represents the asynchronous write operation.
- protected override Task StartPropertyAsync(ODataPropertyInfo property)
+ protected override ValueTask StartPropertyAsync(ODataPropertyInfo property)
{
ResourceBaseScope scope = this.ParentScope as ResourceBaseScope;
Debug.Assert(scope != null, "Writing a property and the parent scope is not a resource");
@@ -1440,9 +1440,9 @@ protected override Task StartPropertyAsync(ODataPropertyInfo property)
///
/// The property to write.
/// A task that represents the asynchronous write operation.
- protected override Task EndPropertyAsync(ODataPropertyInfo property)
+ protected override ValueTask EndPropertyAsync(ODataPropertyInfo property)
{
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -1450,7 +1450,7 @@ protected override Task EndPropertyAsync(ODataPropertyInfo property)
///
/// The resource set to write.
/// A task that represents the asynchronous write operation.
- protected override async Task StartResourceSetAsync(ODataResourceSet resourceSet)
+ protected override async ValueTask StartResourceSetAsync(ODataResourceSet resourceSet)
{
Debug.Assert(resourceSet != null, "resourceSet != null");
@@ -1598,7 +1598,7 @@ await this.jsonWriter.StartArrayScopeAsync()
///
/// The resource set to write.
/// A task that represents the asynchronous write operation.
- protected override async Task EndResourceSetAsync(ODataResourceSet resourceSet)
+ protected override async ValueTask EndResourceSetAsync(ODataResourceSet resourceSet)
{
Debug.Assert(resourceSet != null, "resourceSet != null");
@@ -1668,7 +1668,7 @@ await this.WriteResourceSetNextLinkAsync(resourceSet.NextPageLink, propertyName)
///
/// The delta resource set to write.
/// A task that represents the asynchronous write operation.
- protected override async Task StartDeltaResourceSetAsync(ODataDeltaResourceSet deltaResourceSet)
+ protected override async ValueTask StartDeltaResourceSetAsync(ODataDeltaResourceSet deltaResourceSet)
{
Debug.Assert(deltaResourceSet != null, "resourceSet != null");
@@ -1738,7 +1738,7 @@ await this.jsonWriter.StartArrayScopeAsync()
///
/// The resource set to write.
/// A task that represents the asynchronous write operation.
- protected override Task EndDeltaResourceSetAsync(ODataDeltaResourceSet deltaResourceSet)
+ protected override ValueTask EndDeltaResourceSetAsync(ODataDeltaResourceSet deltaResourceSet)
{
Debug.Assert(deltaResourceSet != null, "deltaResourceSet != null");
@@ -1746,7 +1746,7 @@ protected override Task EndDeltaResourceSetAsync(ODataDeltaResourceSet deltaReso
{
return EndDeltaResourceSetInnerAsync(deltaResourceSet);
- async Task EndDeltaResourceSetInnerAsync(ODataDeltaResourceSet innerDeltaResourceSet)
+ async ValueTask EndDeltaResourceSetInnerAsync(ODataDeltaResourceSet innerDeltaResourceSet)
{
// End the array which holds the entries in the resource set.
await this.jsonWriter.EndArrayScopeAsync()
@@ -1782,7 +1782,7 @@ await this.jsonWriter.EndObjectScopeAsync()
///
/// The resource to write.
/// A task that represents the asynchronous write operation.
- protected override async Task StartDeletedResourceAsync(ODataDeletedResource resource)
+ protected override async ValueTask StartDeletedResourceAsync(ODataDeletedResource resource)
{
Debug.Assert(resource != null, "resource != null");
DeletedResourceScope resourceScope = this.CurrentDeletedResourceScope;
@@ -1856,11 +1856,11 @@ await this.WriteDeletedEntryContentsAsync(resource)
///
/// The resource to write.
/// A task that represents the asynchronous write operation.
- protected override Task EndDeletedResourceAsync(ODataDeletedResource deletedResource)
+ protected override ValueTask EndDeletedResourceAsync(ODataDeletedResource deletedResource)
{
if (deletedResource == null)
{
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
// Close the object scope
@@ -1872,7 +1872,7 @@ protected override Task EndDeletedResourceAsync(ODataDeletedResource deletedReso
///
/// The link to write.
/// A task that represents the asynchronous write operation.
- protected override async Task StartDeltaLinkAsync(ODataDeltaLinkBase link)
+ protected override async ValueTask StartDeltaLinkAsync(ODataDeltaLinkBase link)
{
Debug.Assert(link != null, "link != null");
@@ -1906,7 +1906,7 @@ await this.jsonWriter.EndObjectScopeAsync()
///
/// A task that represents the asynchronous write operation.
/// The value of the TResult parameter contains the for writing the binary value.
- protected override async Task StartBinaryStreamAsync()
+ protected override async ValueTask StartBinaryStreamAsync()
{
ODataPropertyInfo property;
if ((property = this.ParentScope?.Item as ODataPropertyInfo) != null)
@@ -1934,13 +1934,13 @@ await this.jsonWriter.FlushAsync()
/// Asynchronously finish writing a stream value.
///
/// A task that represents the asynchronous write operation.
- protected sealed override Task EndBinaryStreamAsync()
+ protected sealed override ValueTask EndBinaryStreamAsync()
{
if (this.jsonWriter == null)
{
return EndBinaryStreamInnerAsync();
- async Task EndBinaryStreamInnerAsync()
+ async ValueTask EndBinaryStreamInnerAsync()
{
await this.jsonWriter.WriteValueAsync(
this.jsonOutputContext.BinaryValueStream.ToArray()).ConfigureAwait(false);
@@ -1961,7 +1961,7 @@ await this.jsonOutputContext.BinaryValueStream.FlushAsync()
///
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains the for writing a string value.
- protected override async Task StartTextWriterAsync()
+ protected override async ValueTask StartTextWriterAsync()
{
ODataPropertyInfo property;
if ((property = this.ParentScope?.Item as ODataPropertyInfo) != null)
@@ -1988,7 +1988,7 @@ await this.jsonWriter.FlushAsync()
/// Asynchronously finish writing a text value.
///
/// A task that represents the asynchronous write operation.
- protected sealed override Task EndTextWriterAsync()
+ protected sealed override ValueTask EndTextWriterAsync()
{
return this.jsonWriter.EndTextWriterValueScopeAsync();
}
@@ -1998,7 +1998,7 @@ protected sealed override Task EndTextWriterAsync()
///
/// The primitive value to write.
/// A task that represents the asynchronous write operation.
- protected override async Task WritePrimitiveValueAsync(ODataPrimitiveValue primitiveValue)
+ protected override async ValueTask WritePrimitiveValueAsync(ODataPrimitiveValue primitiveValue)
{
ODataPropertyInfo property;
if ((property = this.ParentScope?.Item as ODataPropertyInfo) != null)
@@ -2024,7 +2024,7 @@ await this.jsonValueSerializer.WritePrimitiveValueAsync(primitiveValue.Value, /*
///
/// The nested resource info to write.
/// A task that represents the asynchronous write operation.
- protected override Task WriteDeferredNestedResourceInfoAsync(ODataNestedResourceInfo nestedResourceInfo)
+ protected override ValueTask WriteDeferredNestedResourceInfoAsync(ODataNestedResourceInfo nestedResourceInfo)
{
Debug.Assert(nestedResourceInfo != null, "nestedResourceInfo != null");
Debug.Assert(this.writingResponse, "Deferred links are only supported in response, we should have verified this already.");
@@ -2040,7 +2040,7 @@ protected override Task WriteDeferredNestedResourceInfoAsync(ODataNestedResource
///
/// The nested resource info to write.
/// A task that represents the asynchronous write operation.
- protected override Task StartNestedResourceInfoWithContentAsync(ODataNestedResourceInfo nestedResourceInfo)
+ protected override ValueTask StartNestedResourceInfoWithContentAsync(ODataNestedResourceInfo nestedResourceInfo)
{
Debug.Assert(nestedResourceInfo != null, "nestedResourceInfo != null");
Debug.Assert(!string.IsNullOrEmpty(nestedResourceInfo.Name),
@@ -2050,7 +2050,7 @@ protected override Task StartNestedResourceInfoWithContentAsync(ODataNestedResou
{
return StartNestedResourceInfoWithContentInnerAsync(nestedResourceInfo);
- async Task StartNestedResourceInfoWithContentInnerAsync(ODataNestedResourceInfo innerNestedResourceInfo)
+ async ValueTask StartNestedResourceInfoWithContentInnerAsync(ODataNestedResourceInfo innerNestedResourceInfo)
{
// Write @odata.context annotation for navigation property
IEdmContainedEntitySet containedEntitySet = this.CurrentScope.NavigationSource as IEdmContainedEntitySet;
@@ -2079,7 +2079,7 @@ await this.jsonResourceSerializer.WriteNavigationLinkMetadataAsync(
{
this.WriterValidator.ValidateNestedResourceInfoHasCardinality(nestedResourceInfo);
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
}
@@ -2088,7 +2088,7 @@ await this.jsonResourceSerializer.WriteNavigationLinkMetadataAsync(
///
/// The nested resource info to write.
/// A task that represents the asynchronous write operation.
- protected override Task EndNestedResourceInfoWithContentAsync(ODataNestedResourceInfo nestedResourceInfo)
+ protected override ValueTask EndNestedResourceInfoWithContentAsync(ODataNestedResourceInfo nestedResourceInfo)
{
Debug.Assert(nestedResourceInfo != null, "nestedResourceInfo != null");
@@ -2098,7 +2098,7 @@ protected override Task EndNestedResourceInfoWithContentAsync(ODataNestedResourc
{
return EndNestedResourceInfoWithContentInnerAsync(nestedResourceInfo);
- async Task EndNestedResourceInfoWithContentInnerAsync(ODataNestedResourceInfo innerNestedResourceInfo)
+ async ValueTask EndNestedResourceInfoWithContentInnerAsync(ODataNestedResourceInfo innerNestedResourceInfo)
{
JsonNestedResourceInfoScope navigationLinkScope = (JsonNestedResourceInfoScope)this.CurrentScope;
@@ -2119,7 +2119,7 @@ await this.jsonWriter.EndArrayScopeAsync()
}
}
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -2128,7 +2128,7 @@ await this.jsonWriter.EndArrayScopeAsync()
/// The parent navigation link which is being written around the entity reference link.
/// The entity reference link to write.
/// A task that represents the asynchronous write operation.
- protected override async Task WriteEntityReferenceInNavigationLinkContentAsync(
+ protected override async ValueTask WriteEntityReferenceInNavigationLinkContentAsync(
ODataNestedResourceInfo parentNestedResourceInfo,
ODataEntityReferenceLink entityReferenceLink)
{
@@ -2214,28 +2214,19 @@ await WriteEntityReferenceLinkImplementationAsync(entityReferenceLink)
/// True if writing response.
/// The selected properties of this scope.
/// A task that represents the asynchronous operation.
- protected override Task PrepareResourceForWriteStartAsync(
+ protected override ValueTask PrepareResourceForWriteStartAsync(
ResourceScope resourceScope,
ODataResource resource,
bool writingResponse,
SelectedPropertiesNode selectedProperties)
{
// Currently, no asynchronous operation is involved when preparing resource for writing
- return TaskUtils.GetTaskForSynchronousOperation((
- thisParam,
- resourceScopeParam,
- resourceParam,
- writingResponseParam,
- selectedPropertiesParam) => thisParam.PrepareResourceForWriteStart(
- resourceScopeParam,
- resourceParam,
- writingResponseParam,
- selectedPropertiesParam),
- this,
+ this.PrepareResourceForWriteStart(
resourceScope,
resource,
writingResponse,
selectedProperties);
+ return ValueTask.CompletedTask;
}
///
@@ -2247,28 +2238,19 @@ protected override Task PrepareResourceForWriteStartAsync(
/// True if writing response.
/// The selected properties of this scope.
/// A task that represents the asynchronous operation.
- protected override Task PrepareDeletedResourceForWriteStartAsync(
+ protected override ValueTask PrepareDeletedResourceForWriteStartAsync(
DeletedResourceScope resourceScope,
ODataDeletedResource deletedResource,
bool writingResponse,
SelectedPropertiesNode selectedProperties)
{
// Currently, no asynchronous operation is involved when preparing deleted resource for writing
- return TaskUtils.GetTaskForSynchronousOperation((
- thisParam,
- resourceScopeParam,
- deletedResourceParam,
- writingResponseParam,
- selectedPropertiesParam) => this.PrepareDeletedResourceForWriteStart(
- resourceScopeParam,
- deletedResourceParam,
- writingResponseParam,
- selectedPropertiesParam),
- this,
+ this.PrepareDeletedResourceForWriteStart(
resourceScope,
deletedResource,
writingResponse,
selectedProperties);
+ return ValueTask.CompletedTask;
}
///
@@ -2625,7 +2607,7 @@ private void ValidateNoCustomInstanceAnnotationsForExpandedResourceSet(ODataReso
///
/// The OData entity reference link.
/// A task that represents the asynchronous write operation.
- private async Task WriteEntityReferenceLinkImplementationAsync(ODataEntityReferenceLink entityReferenceLink)
+ private async ValueTask WriteEntityReferenceLinkImplementationAsync(ODataEntityReferenceLink entityReferenceLink)
{
Debug.Assert(entityReferenceLink != null, "entityReferenceLink != null");
@@ -2656,13 +2638,13 @@ await this.jsonWriter.EndObjectScopeAsync()
/// The count to write for the resource set.
/// The name of the expanded nav property or null for a top-level resource set.
/// A task that represents the asynchronous write operation.
- private Task WriteResourceSetCountAsync(long? count, string propertyName)
+ private ValueTask WriteResourceSetCountAsync(long? count, string propertyName)
{
if (count.HasValue)
{
return WriteResourceSetCountInnerAsync(count.Value, propertyName);
- async Task WriteResourceSetCountInnerAsync(long innerCount, string innerPropertyName)
+ async ValueTask WriteResourceSetCountInnerAsync(long innerCount, string innerPropertyName)
{
if (innerPropertyName == null)
{
@@ -2681,7 +2663,7 @@ await this.jsonWriter.WriteValueAsync(innerCount)
}
}
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -2690,7 +2672,7 @@ await this.jsonWriter.WriteValueAsync(innerCount)
/// The nextLink to write, if available.
/// The name of the expanded nav property or null for a top-level resource set.
/// A task that represents the asynchronous write operation.
- private Task WriteResourceSetNextLinkAsync(Uri nextPageLink, string propertyName)
+ private ValueTask WriteResourceSetNextLinkAsync(Uri nextPageLink, string propertyName)
{
bool nextPageWritten = this.State == WriterState.ResourceSet ?
this.CurrentResourceSetScope.NextPageLinkWritten :
@@ -2700,7 +2682,7 @@ private Task WriteResourceSetNextLinkAsync(Uri nextPageLink, string propertyName
{
return WriteResourceSetNextLinkInnerAsync(nextPageLink, propertyName);
- async Task WriteResourceSetNextLinkInnerAsync(Uri innerNextPageLink, string innerPropertyName)
+ async ValueTask WriteResourceSetNextLinkInnerAsync(Uri innerNextPageLink, string innerPropertyName)
{
if (innerPropertyName == null)
{
@@ -2728,7 +2710,7 @@ await this.jsonWriter.WriteValueAsync(
}
}
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -2737,11 +2719,11 @@ await this.jsonWriter.WriteValueAsync(
///
/// The delta link to write.
/// A task that represents the asynchronous write operation.
- private Task WriteResourceSetDeltaLinkAsync(Uri deltaLink)
+ private ValueTask WriteResourceSetDeltaLinkAsync(Uri deltaLink)
{
if (deltaLink == null)
{
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
Debug.Assert(this.State == WriterState.ResourceSet || this.State == WriterState.DeltaResourceSet,
@@ -2755,7 +2737,7 @@ private Task WriteResourceSetDeltaLinkAsync(Uri deltaLink)
{
return WriteResourceSetDeltaLinkInnerAsync(deltaLink);
- async Task WriteResourceSetDeltaLinkInnerAsync(Uri innerDeltaLink)
+ async ValueTask WriteResourceSetDeltaLinkInnerAsync(Uri innerDeltaLink)
{
await this.odataAnnotationWriter.WriteInstanceAnnotationNameAsync(
ODataAnnotationNames.ODataDeltaLink).ConfigureAwait(false);
@@ -2773,7 +2755,7 @@ await this.jsonWriter.WriteValueAsync(
}
}
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -2781,7 +2763,7 @@ await this.jsonWriter.WriteValueAsync(
///
/// The deleted resource to write deleted entry contents for
/// A task that represents the asynchronous write operation.
- private async Task WriteV4DeletedEntryContentsAsync(ODataDeletedResource resource)
+ private async ValueTask WriteV4DeletedEntryContentsAsync(ODataDeletedResource resource)
{
await this.WriteDeletedResourceIdAsync(resource)
.ConfigureAwait(false);
@@ -2794,7 +2776,7 @@ await this.WriteDeltaResourceReasonAsync(resource)
///
/// The deleted resource to write deleted entry contents for
/// A task that represents the asynchronous write operation.
- private async Task WriteDeletedEntryContentsAsync(ODataDeletedResource resource)
+ private async ValueTask WriteDeletedEntryContentsAsync(ODataDeletedResource resource)
{
await this.odataAnnotationWriter.WriteInstanceAnnotationNameAsync(
ODataAnnotationNames.ODataRemoved).ConfigureAwait(false);
@@ -2831,7 +2813,7 @@ await this.WriteDeltaResourcePropertiesAsync(resource)
///
/// The resource to write the id for.
/// A task that represents the asynchronous write operation.
- private async Task WriteDeletedResourceIdAsync(ODataDeletedResource resource)
+ private async ValueTask WriteDeletedResourceIdAsync(ODataDeletedResource resource)
{
Debug.Assert(resource != null, "resource != null");
if (this.Version == null || this.Version < ODataVersion.V401)
@@ -2885,7 +2867,7 @@ private Task WriteDeltaResourcePropertiesAsync(ODataResourceBase resource)
///
/// The resource to write the reason for.
/// A task that represents the asynchronous write operation.
- private async Task WriteDeltaResourceReasonAsync(ODataDeletedResource resource)
+ private async ValueTask WriteDeltaResourceReasonAsync(ODataDeletedResource resource)
{
Debug.Assert(resource != null, "resource != null");
@@ -2918,7 +2900,7 @@ await this.jsonWriter.WriteValueAsync(ODataJsonConstants.ODataReasonChangedValue
///
/// The delta kind of link.
/// A task that represents the asynchronous write operation.
- private Task WriteDeltaLinkContextUriAsync(ODataDeltaKind kind)
+ private ValueTask WriteDeltaLinkContextUriAsync(ODataDeltaKind kind)
{
Debug.Assert(kind == ODataDeltaKind.Link || kind == ODataDeltaKind.DeletedLink,
"kind must be either DeltaLink or DeltaDeletedLink.");
@@ -2931,7 +2913,7 @@ private Task WriteDeltaLinkContextUriAsync(ODataDeltaKind kind)
///
/// The link to write source for.
/// A task that represents the asynchronous write operation.
- private async Task WriteDeltaLinkSourceAsync(ODataDeltaLinkBase link)
+ private async ValueTask WriteDeltaLinkSourceAsync(ODataDeltaLinkBase link)
{
Debug.Assert(link != null, "link != null");
Debug.Assert(link is ODataDeltaLink || link is ODataDeltaDeletedLink,
@@ -2948,7 +2930,7 @@ await this.jsonWriter.WriteValueAsync(UriUtils.UriToString(link.Source))
///
/// The link to write relationship for.
/// A task that represents the asynchronous write operation.
- private async Task WriteDeltaLinkRelationshipAsync(ODataDeltaLinkBase link)
+ private async ValueTask WriteDeltaLinkRelationshipAsync(ODataDeltaLinkBase link)
{
Debug.Assert(link != null, "link != null");
Debug.Assert(link is ODataDeltaLink || link is ODataDeltaDeletedLink,
@@ -2965,7 +2947,7 @@ await this.jsonWriter.WriteValueAsync(link.Relationship)
///
/// The link to write target for.
/// A task that represents the asynchronous write operation.
- private async Task WriteDeltaLinkTargetAsync(ODataDeltaLinkBase link)
+ private async ValueTask WriteDeltaLinkTargetAsync(ODataDeltaLinkBase link)
{
Debug.Assert(link != null, "link != null");
Debug.Assert(link is ODataDeltaLink || link is ODataDeltaDeletedLink,
diff --git a/src/Microsoft.OData.Core/Json/ODataJsonWriterUtils.cs b/src/Microsoft.OData.Core/Json/ODataJsonWriterUtils.cs
index be4bb03b9a..28fa170694 100644
--- a/src/Microsoft.OData.Core/Json/ODataJsonWriterUtils.cs
+++ b/src/Microsoft.OData.Core/Json/ODataJsonWriterUtils.cs
@@ -131,9 +131,9 @@ internal static void ODataValueToString(StringBuilder sb, ODataValue value)
/// A flag indicating whether error details should be written (in debug mode only) or not.
/// The maximum number of nested inner errors to allow.
/// A task that represents the asynchronous write operation.
- internal static Task WriteErrorAsync(
+ internal static ValueTask WriteErrorAsync(
IJsonWriter jsonWriter,
- Func, Task> writeInstanceAnnotationsDelegate,
+ Func, ValueTask> writeInstanceAnnotationsDelegate,
ODataError error,
bool includeDebugInformation,
int maxInnerErrorDepth)
@@ -394,7 +394,7 @@ private static void ODataResourceValueToString(StringBuilder sb, ODataResourceVa
/// Delegate to write the instance annotations.
/// The maximum number of nested inner errors to allow.
/// A task that represents the asynchronous write operation.
- private static async Task WriteErrorAsync(
+ private static async ValueTask WriteErrorAsync(
IJsonWriter jsonWriter,
string code,
string message,
@@ -402,7 +402,7 @@ private static async Task WriteErrorAsync(
IEnumerable details,
ODataInnerError innerError,
ICollection instanceAnnotations,
- Func, Task> writeInstanceAnnotationsDelegate,
+ Func, ValueTask> writeInstanceAnnotationsDelegate,
int maxInnerErrorDepth)
{
Debug.Assert(jsonWriter != null, "jsonWriter != null");
@@ -463,7 +463,7 @@ await WriteInnerErrorAsync(jsonWriter, innerError, JsonConstants.ODataErrorInner
/// The details of the error.
/// The property name for the error details property.
/// A task that represents the asynchronous write operation.
- private static async Task WriteErrorDetailsAsync(IJsonWriter jsonWriter, IEnumerable details,
+ private static async ValueTask WriteErrorDetailsAsync(IJsonWriter jsonWriter, IEnumerable details,
string odataErrorDetailsName)
{
Debug.Assert(jsonWriter != null, "jsonWriter != null");
@@ -511,7 +511,7 @@ private static async Task WriteErrorDetailsAsync(IJsonWriter jsonWriter, IEnumer
/// The number of times this method has been called recursively.
/// The maximum number of nested inner errors to allow.
/// A task that represents the asynchronous write operation.
- private static async Task WriteInnerErrorAsync(IJsonWriter jsonWriter, ODataInnerError innerError,
+ private static async ValueTask WriteInnerErrorAsync(IJsonWriter jsonWriter, ODataInnerError innerError,
string innerErrorPropertyName, int recursionDepth, int maxInnerErrorDepth)
{
Debug.Assert(jsonWriter != null, "jsonWriter != null");
@@ -598,7 +598,7 @@ internal static void WriteInstanceAnnotationName(this IJsonWriter jsonWriter, st
/// Writes the 'value' property name asynchronously.
///
/// The JSON writer to write to.
- internal static Task WriteValuePropertyNameAsync(this IJsonWriter jsonWriter)
+ internal static ValueTask WriteValuePropertyNameAsync(this IJsonWriter jsonWriter)
{
Debug.Assert(jsonWriter != null, "jsonWriter != null");
@@ -611,7 +611,7 @@ internal static Task WriteValuePropertyNameAsync(this IJsonWriter jsonWriter)
/// The JSON writer to write to.
/// The name of the property to annotate.
/// The name of the annotation to write.
- internal static Task WritePropertyAnnotationNameAsync(this IJsonWriter jsonWriter, string propertyName, string annotationName)
+ internal static ValueTask WritePropertyAnnotationNameAsync(this IJsonWriter jsonWriter, string propertyName, string annotationName)
{
Debug.Assert(jsonWriter != null, "jsonWriter != null");
Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)");
@@ -625,7 +625,7 @@ internal static Task WritePropertyAnnotationNameAsync(this IJsonWriter jsonWrite
///
/// The JSON writer to write to.
/// The name of the instance annotation to write.
- internal static Task WriteInstanceAnnotationNameAsync(this IJsonWriter jsonWriter, string annotationName)
+ internal static ValueTask WriteInstanceAnnotationNameAsync(this IJsonWriter jsonWriter, string annotationName)
{
Debug.Assert(jsonWriter != null, "jsonWriter != null");
Debug.Assert(!string.IsNullOrEmpty(annotationName), "!string.IsNullOrEmpty(annotationName)");
diff --git a/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.Stream.cs b/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.Stream.cs
index a173837dbe..1f71c6be66 100644
--- a/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.Stream.cs
+++ b/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.Stream.cs
@@ -58,7 +58,7 @@ public void EndStreamValueScope()
/// Asynchronously starts a scope for writing a stream value.
///
/// A task representing the asynchronous operation. The task result contains a stream for writing the stream value.
- public async Task StartStreamValueScopeAsync()
+ public async ValueTask StartStreamValueScopeAsync()
{
this.WriteSeparatorIfNecessary();
this.bufferWriter.Write(this.DoubleQuote.Slice(0, 1).Span);
@@ -73,7 +73,7 @@ public async Task StartStreamValueScopeAsync()
/// Asynchronously ends a scope for writing a stream value.
///
/// A task representing the asynchronous operation.
- public async Task EndStreamValueScopeAsync()
+ public async ValueTask EndStreamValueScopeAsync()
{
if (this.binaryValueStream != null)
{
diff --git a/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.TextWriter.cs b/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.TextWriter.cs
index 1414222ad8..51d00fcef5 100644
--- a/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.TextWriter.cs
+++ b/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.TextWriter.cs
@@ -83,7 +83,7 @@ public void EndTextWriterValueScope()
///
/// The content type of the TextWriter value scope.
/// A task representing the asynchronous operation. The task result is a TextWriter for writing JSON data.
- public async Task StartTextWriterValueScopeAsync(string contentType)
+ public async ValueTask StartTextWriterValueScopeAsync(string contentType)
{
await this.FlushAsync().ConfigureAwait(false);
@@ -109,7 +109,7 @@ public async Task StartTextWriterValueScopeAsync(string contentType)
/// Asynchronously ends a TextWriter value scope.
///
/// A task representing the asynchronous operation.
- public async Task EndTextWriterValueScopeAsync()
+ public async ValueTask EndTextWriterValueScopeAsync()
{
if (!this.isWritingJson)
{
diff --git a/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.cs b/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.cs
index d0d8785057..6f4bc03c42 100644
--- a/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.cs
+++ b/src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.cs
@@ -861,28 +861,28 @@ public void Dispose()
#region "Asynchronous API"
- public async Task StartPaddingFunctionScopeAsync()
+ public async ValueTask StartPaddingFunctionScopeAsync()
{
this.CommitUtf8JsonWriterContentsToBuffer();
this.bufferWriter.Write(parentheses[..1].Span);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WritePaddingFunctionNameAsync(string functionName)
+ public async ValueTask WritePaddingFunctionNameAsync(string functionName)
{
this.CommitUtf8JsonWriterContentsToBuffer();
this.bufferWriter.Write(Encoding.UTF8.GetBytes(functionName));
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task EndPaddingFunctionScopeAsync()
+ public async ValueTask EndPaddingFunctionScopeAsync()
{
this.CommitUtf8JsonWriterContentsToBuffer();
this.bufferWriter.Write(parentheses[1..2].Span);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task StartObjectScopeAsync()
+ public async ValueTask StartObjectScopeAsync()
{
this.WriteSeparatorIfNecessary();
this.EnterObjectScope();
@@ -890,14 +890,14 @@ public async Task StartObjectScopeAsync()
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task EndObjectScopeAsync()
+ public async ValueTask EndObjectScopeAsync()
{
this.utf8JsonWriter.WriteEndObject();
this.ExitScope();
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task StartArrayScopeAsync()
+ public async ValueTask StartArrayScopeAsync()
{
this.WriteSeparatorIfNecessary();
this.EnterArrayScope();
@@ -905,49 +905,49 @@ public async Task StartArrayScopeAsync()
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task EndArrayScopeAsync()
+ public async ValueTask EndArrayScopeAsync()
{
this.utf8JsonWriter.WriteEndArray();
this.ExitScope();
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteNameAsync(string name)
+ public async ValueTask WriteNameAsync(string name)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WritePropertyName(name);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(bool value)
+ public async ValueTask WriteValueAsync(bool value)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WriteBooleanValue(value);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(int value)
+ public async ValueTask WriteValueAsync(int value)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WriteNumberValue(value);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(float value)
+ public async ValueTask WriteValueAsync(float value)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WriteNumberValue(value);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(short value)
+ public async ValueTask WriteValueAsync(short value)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WriteNumberValue(value);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(long value)
+ public async ValueTask WriteValueAsync(long value)
{
this.WriteSeparatorIfNecessary();
if (this.isIeee754Compatible)
@@ -962,7 +962,7 @@ public async Task WriteValueAsync(long value)
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(double value)
+ public async ValueTask WriteValueAsync(double value)
{
this.WriteSeparatorIfNecessary();
if (double.IsNaN(value))
@@ -985,14 +985,14 @@ public async Task WriteValueAsync(double value)
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(Guid value)
+ public async ValueTask WriteValueAsync(Guid value)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WriteStringValue(value);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(decimal value)
+ public async ValueTask WriteValueAsync(decimal value)
{
this.WriteSeparatorIfNecessary();
if (this.isIeee754Compatible)
@@ -1007,7 +1007,7 @@ public async Task WriteValueAsync(decimal value)
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(DateTimeOffset value)
+ public async ValueTask WriteValueAsync(DateTimeOffset value)
{
this.WriteSeparatorIfNecessary();
if (value.Offset == TimeSpan.Zero)
@@ -1029,7 +1029,7 @@ public async Task WriteValueAsync(DateTimeOffset value)
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(TimeSpan value)
+ public async ValueTask WriteValueAsync(TimeSpan value)
{
this.WriteSeparatorIfNecessary();
string stringValue = EdmValueWriter.DurationAsXml(value);
@@ -1037,35 +1037,35 @@ public async Task WriteValueAsync(TimeSpan value)
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(Date value)
+ public async ValueTask WriteValueAsync(Date value)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WriteStringValue(value.ToString());
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(TimeOfDay value)
+ public async ValueTask WriteValueAsync(TimeOfDay value)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WriteStringValue(value.ToString());
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(byte value)
+ public async ValueTask WriteValueAsync(byte value)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WriteNumberValue(value);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(sbyte value)
+ public async ValueTask WriteValueAsync(sbyte value)
{
this.WriteSeparatorIfNecessary();
this.utf8JsonWriter.WriteNumberValue(value);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteValueAsync(string value)
+ public async ValueTask WriteValueAsync(string value)
{
if (value == null)
{
@@ -1138,7 +1138,7 @@ private async ValueTask WriteStringValueInChunksAsync(ReadOnlyMemory value
CheckIfManualValueAtArrayStart();
}
- public async Task WriteValueAsync(byte[] value)
+ public async ValueTask WriteValueAsync(byte[] value)
{
if (value == null)
{
@@ -1195,14 +1195,14 @@ private async ValueTask WriteByteValueInChunksAsync(ReadOnlyMemory value)
CheckIfManualValueAtArrayStart();
}
- public async Task WriteValueAsync(JsonElement value)
+ public async ValueTask WriteValueAsync(JsonElement value)
{
this.WriteSeparatorIfNecessary();
value.WriteTo(utf8JsonWriter);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
}
- public async Task WriteRawValueAsync(string rawValue)
+ public async ValueTask WriteRawValueAsync(string rawValue)
{
this.WriteRawValueCore(rawValue);
await this.FlushIfBufferThresholdReachedAsync().ConfigureAwait(false);
diff --git a/src/Microsoft.OData.Core/Json/ReorderingJsonReader.cs b/src/Microsoft.OData.Core/Json/ReorderingJsonReader.cs
index 83fa879acd..c5da565ce6 100644
--- a/src/Microsoft.OData.Core/Json/ReorderingJsonReader.cs
+++ b/src/Microsoft.OData.Core/Json/ReorderingJsonReader.cs
@@ -91,7 +91,7 @@ public override bool CanStream()
/// The value of the TResult parameter contains a used to read a stream value.
///
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1825:Avoid zero-length array allocations.", Justification = "")]
- public override async Task CreateReadStreamAsync()
+ public override async ValueTask CreateReadStreamAsync()
{
Stream result;
object value = null;
@@ -128,7 +128,7 @@ await this.ReadAsync()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains a for reading the text value.
///
- public override async Task CreateTextReaderAsync()
+ public override async ValueTask CreateTextReaderAsync()
{
if (this.NodeType == JsonNodeType.Property)
{
@@ -154,7 +154,7 @@ await this.ReadAsync()
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains true if the current value can be streamed; otherwise false.
///
- public override async Task CanStreamAsync()
+ public override async ValueTask CanStreamAsync()
{
object value = await this.GetValueAsync()
.ConfigureAwait(false);
@@ -269,7 +269,7 @@ protected override void ProcessObjectValue()
/// once it returns the reader will be returned to the position before the method was called.
/// The reader is always positioned on a start object when this method is called.
///
- protected override async Task ProcessObjectValueAsync()
+ protected override async ValueTask ProcessObjectValueAsync()
{
Debug.Assert(this.currentBufferedNode.NodeType == JsonNodeType.StartObject, "this.currentBufferedNode.NodeType == JsonNodeType.StartObject");
this.AssertBuffering();
diff --git a/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchFormat.cs b/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchFormat.cs
index 12b8e363b1..e968e2a666 100644
--- a/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchFormat.cs
+++ b/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchFormat.cs
@@ -83,12 +83,12 @@ public override ODataOutputContext CreateOutputContext(
/// Configuration settings of the OData reader.
/// A task that when completed returns the set of s
/// that are supported with the specified payload.
- public override Task> DetectPayloadKindAsync(
+ public override ValueTask> DetectPayloadKindAsync(
ODataMessageInfo messageInfo,
ODataMessageReaderSettings settings)
{
ExceptionUtils.CheckArgumentNotNull(messageInfo, "messageInfo");
- return TaskUtils.GetTaskForSynchronousOperation(() => DetectPayloadKindImplementation(messageInfo.MediaType));
+ return ValueTask.FromResult(DetectPayloadKindImplementation(messageInfo.MediaType));
}
///
@@ -97,14 +97,14 @@ public override Task> DetectPayloadKindAsync(
/// The context information for the message.
/// Configuration settings of the OData reader.
/// Task which when completed returned the newly created input context.
- public override Task CreateInputContextAsync(
+ public override ValueTask CreateInputContextAsync(
ODataMessageInfo messageInfo,
ODataMessageReaderSettings messageReaderSettings)
{
ExceptionUtils.CheckArgumentNotNull(messageInfo, "messageInfo");
ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings");
- return Task.FromResult(
+ return ValueTask.FromResult(
new ODataMultipartMixedBatchInputContext(this, messageInfo, messageReaderSettings));
}
@@ -114,14 +114,14 @@ public override Task CreateInputContextAsync(
/// The context information for the message.
/// Configuration settings of the OData writer.
/// Task which represents the pending create operation.
- public override Task CreateOutputContextAsync(
+ public override ValueTask CreateOutputContextAsync(
ODataMessageInfo messageInfo,
ODataMessageWriterSettings messageWriterSettings)
{
ExceptionUtils.CheckArgumentNotNull(messageInfo, "messageInfo");
ExceptionUtils.CheckArgumentNotNull(messageWriterSettings, "messageWriterSettings");
- return Task.FromResult(
+ return ValueTask.FromResult(
new ODataMultipartMixedBatchOutputContext(this, messageInfo, messageWriterSettings));
}
diff --git a/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchInputContext.cs b/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchInputContext.cs
index 29ec177de1..10cde338b5 100644
--- a/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchInputContext.cs
+++ b/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchInputContext.cs
@@ -63,10 +63,10 @@ internal override ODataBatchReader CreateBatchReader()
/// Asynchronously create a .
///
/// Task which when completed returns the newly created .
- internal override Task CreateBatchReaderAsync()
+ internal override ValueTask CreateBatchReaderAsync()
{
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
- return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateBatchReaderImplementation(/*synchronous*/ false));
+ return ValueTask.FromResult(this.CreateBatchReaderImplementation(synchronous: false));
}
///
diff --git a/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchOutputContext.cs b/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchOutputContext.cs
index 751ea5ae9e..1249355871 100644
--- a/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchOutputContext.cs
+++ b/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchOutputContext.cs
@@ -56,13 +56,11 @@ internal override ODataBatchWriter CreateODataBatchWriter()
/// A running task for the created batch writer.
/// We don't plan to make this public!
/// The write must flush the output when it's finished (inside the last Write call).
- internal override Task CreateODataBatchWriterAsync()
+ internal override ValueTask CreateODataBatchWriterAsync()
{
this.AssertAsynchronous();
- return TaskUtils.GetTaskForSynchronousOperation(
- thisParam => thisParam.CreateODataBatchWriterImplementation(),
- this);
+ return ValueTask.FromResult(this.CreateODataBatchWriterImplementation());
}
///
diff --git a/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchWriter.cs b/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchWriter.cs
index 2e92919128..40c9e3cece 100644
--- a/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchWriter.cs
+++ b/src/Microsoft.OData.Core/MultipartMixed/ODataMultipartMixedBatchWriter.cs
@@ -115,7 +115,7 @@ public override void StreamRequested()
/// A task representing any action that is running as part of the status change of the operation;
/// null if no such action exists.
///
- public override async Task StreamRequestedAsync()
+ public override async ValueTask StreamRequestedAsync()
{
// Write any pending data and flush the batch writer to the async buffered stream
await this.StartBatchOperationContentAsync()
@@ -146,11 +146,10 @@ public override void StreamDisposed()
this.RawOutputContext.InitializeRawValueWriter();
}
- public override Task StreamDisposedAsync()
+ public override ValueTask StreamDisposedAsync()
{
- return TaskUtils.GetTaskForSynchronousOperation(
- thisParam => thisParam.StreamDisposed(),
- this);
+ this.StreamDisposed();
+ return ValueTask.CompletedTask;
}
///
@@ -172,7 +171,7 @@ public override void OnInStreamError()
throw new ODataException(Strings.ODataBatchWriter_CannotWriteInStreamErrorForBatch);
}
- public override async Task OnInStreamErrorAsync()
+ public override async ValueTask OnInStreamErrorAsync()
{
this.RawOutputContext.VerifyNotDisposed();
this.SetState(BatchWriterState.Error);
@@ -401,7 +400,7 @@ protected override void WriteStartBatchImplementation()
/// Asynchronously ends a batch - implementation of the actual functionality.
///
/// A task that represents the asynchronous write operation.
- protected override async Task WriteEndBatchImplementationAsync()
+ protected override async ValueTask WriteEndBatchImplementationAsync()
{
Debug.Assert(
this.batchStartBoundaryWritten || this.CurrentOperationMessage == null,
@@ -430,7 +429,7 @@ await this.RawOutputContext.TextWriter.WriteLineAsync()
///
/// The value for changeset boundary for multipart batch.
/// A task that represents the asynchronous write operation.
- protected override async Task WriteStartChangesetImplementationAsync(string changesetId)
+ protected override async ValueTask WriteStartChangesetImplementationAsync(string changesetId)
{
Debug.Assert(changesetId != null, "changesetId != null");
@@ -463,7 +462,7 @@ await ODataMultipartMixedBatchWriterUtils.WriteChangesetPreambleAsync(
/// Asynchronously ends an active changeset - implementation of the actual functionality.
///
/// A task that represents the asynchronous write operation.
- protected override async Task WriteEndChangesetImplementationAsync()
+ protected override async ValueTask WriteEndChangesetImplementationAsync()
{
// Write pending message data (headers, response line) for a previously unclosed message/request
await this.WritePendingMessageDataAsync(true)
@@ -507,7 +506,7 @@ await ODataMultipartMixedBatchWriterUtils.WriteEndBoundaryAsync(
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains an
/// that can be used to write the request operation.
- protected override async Task CreateOperationRequestMessageImplementationAsync(
+ protected override async ValueTask CreateOperationRequestMessageImplementationAsync(
string method, Uri uri, string contentId, BatchPayloadUriOption payloadUriOption,
IEnumerable dependsOnIds)
{
@@ -555,7 +554,7 @@ await ODataMultipartMixedBatchWriterUtils.WriteRequestPreambleAsync(
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains an
/// that can be used to write the response operation.
- protected override async Task CreateOperationResponseMessageImplementationAsync(string contentId)
+ protected override async ValueTask CreateOperationResponseMessageImplementationAsync(string contentId)
{
await this.WritePendingMessageDataAsync(true)
.ConfigureAwait(false);
@@ -673,7 +672,7 @@ private void WritePendingMessageData(bool reportMessageCompleted)
/// Asynchronously writes all the pending headers and prepares the writer to write a content of the operation.
///
/// A task that represents the asynchronous write operation.
- private async Task StartBatchOperationContentAsync()
+ private async ValueTask StartBatchOperationContentAsync()
{
Debug.Assert(this.CurrentOperationMessage != null, "Expected non-null operation message!");
Debug.Assert(this.RawOutputContext.TextWriter != null, "Must have a batch writer!");
@@ -692,7 +691,7 @@ await this.RawOutputContext.TextWriter.FlushAsync()
/// Asynchronously writes the start boundary for an operation. This is either the batch or the changeset boundary.
///
/// A task that represents the asynchronous write operation.
- private async Task WriteStartBoundaryForOperationAsync()
+ private async ValueTask WriteStartBoundaryForOperationAsync()
{
if (this.changeSetBoundary == null)
{
@@ -719,7 +718,7 @@ await ODataMultipartMixedBatchWriterUtils.WriteStartBoundaryAsync(
/// A flag to control whether after writing the pending data we report writing the message to be completed or not.
///
/// A task that represents the asynchronous write operation.
- private async Task WritePendingMessageDataAsync(bool reportMessageCompleted)
+ private async ValueTask WritePendingMessageDataAsync(bool reportMessageCompleted)
{
if (this.CurrentOperationMessage != null)
{
diff --git a/src/Microsoft.OData.Core/ODataAsynchronousReader.cs b/src/Microsoft.OData.Core/ODataAsynchronousReader.cs
index 2bcab50cdc..9d45739dbb 100644
--- a/src/Microsoft.OData.Core/ODataAsynchronousReader.cs
+++ b/src/Microsoft.OData.Core/ODataAsynchronousReader.cs
@@ -67,7 +67,7 @@ public ODataAsynchronousResponseMessage CreateResponseMessage()
/// Asynchronously returns a message for reading the content of an async response.
///
/// A response message for reading the content of the async response.
- public Task CreateResponseMessageAsync()
+ public ValueTask CreateResponseMessageAsync()
{
this.VerifyCanCreateResponseMessage(false);
@@ -312,9 +312,9 @@ private int ReadByte()
/// A task that represents the asynchronous read operation.
/// The value of the TResult parameter contains the message that can be used to read the response.
///
- private async Task CreateResponseMessageImplementationAsync()
+ private async ValueTask CreateResponseMessageImplementationAsync()
{
- Tuple> readInnerEnvelopeResult = await this.ReadInnerEnvelopeAsync()
+ (int, Dictionary) readInnerEnvelopeResult = await this.ReadInnerEnvelopeAsync()
.ConfigureAwait(false);
int statusCode = readInnerEnvelopeResult.Item1;
@@ -332,7 +332,7 @@ private async Task CreateResponseMessageImplem
/// 1). The status code to use for the async response message.
/// 2). The headers to use for the async response message.
///
- private async Task>> ReadInnerEnvelopeAsync()
+ private async ValueTask<(int, Dictionary)> ReadInnerEnvelopeAsync()
{
string responseLine = await this.ReadFirstNonEmptyLineAsync()
.ConfigureAwait(false);
@@ -342,7 +342,7 @@ private async Task>> ReadInnerEnvelopeAsyn
Dictionary headers = await this.ReadHeadersAsync()
.ConfigureAwait(false);
- return Tuple.Create(statusCode, headers);
+ return (statusCode, headers);
}
///
diff --git a/src/Microsoft.OData.Core/ODataAsynchronousResponseMessage.cs b/src/Microsoft.OData.Core/ODataAsynchronousResponseMessage.cs
index 8756cd93e6..2e21d49b20 100644
--- a/src/Microsoft.OData.Core/ODataAsynchronousResponseMessage.cs
+++ b/src/Microsoft.OData.Core/ODataAsynchronousResponseMessage.cs
@@ -32,7 +32,7 @@ public sealed class ODataAsynchronousResponseMessage : IServiceCollectionProvide
private readonly Action writeEnvelope;
/// The action to write envelope for the inner message asynchronously before returning the stream.
- private readonly Func writeEnvelopeAsync;
+ private readonly Func writeEnvelopeAsync;
/// The dependency injection container to get related services.
private readonly IServiceProvider container;
@@ -104,7 +104,7 @@ private ODataAsynchronousResponseMessage(
Stream stream,
int statusCode,
IDictionary headers,
- Func writeEnvelopeAsync,
+ Func writeEnvelopeAsync,
bool writing,
IServiceProvider container)
: this(stream, statusCode, headers, writing, container)
@@ -206,7 +206,7 @@ public Stream GetStream()
/// Asynchronously get the stream backing for this message.
/// The stream backing for this message.
- public async Task GetStreamAsync()
+ public async ValueTask GetStreamAsync()
{
// If writing response, the envelope for the inner message should be written once and only once before returning the stream.
if (this.writing && !this.envelopeWritten)
@@ -244,12 +244,12 @@ internal static ODataAsynchronousResponseMessage CreateMessageForWriting(Stream
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains an
/// that can be used to write the response content.
- internal static Task CreateMessageForWritingAsync(
+ internal static ValueTask CreateMessageForWritingAsync(
Stream outputStream,
- Func writeEnvelopeAsync,
+ Func writeEnvelopeAsync,
IServiceProvider container)
{
- return Task.FromResult(
+ return ValueTask.FromResult(
new ODataAsynchronousResponseMessage(outputStream, /*statusCode*/ 0, /*headers*/ null, writeEnvelopeAsync, /*writing*/ true, container));
}
diff --git a/src/Microsoft.OData.Core/ODataAsynchronousWriter.cs b/src/Microsoft.OData.Core/ODataAsynchronousWriter.cs
index f28c7051a0..02e538518a 100644
--- a/src/Microsoft.OData.Core/ODataAsynchronousWriter.cs
+++ b/src/Microsoft.OData.Core/ODataAsynchronousWriter.cs
@@ -62,7 +62,7 @@ public ODataAsynchronousResponseMessage CreateResponseMessage()
/// Asynchronously creates a message for writing an async response.
///
/// The message that can be used to write the async response.
- public Task CreateResponseMessageAsync()
+ public ValueTask CreateResponseMessageAsync()
{
this.VerifyCanCreateResponseMessage(false);
@@ -102,7 +102,7 @@ void IODataOutputInStreamErrorListener.OnInStreamError()
}
///
- async Task IODataOutputInStreamErrorListener.OnInStreamErrorAsync()
+ async ValueTask IODataOutputInStreamErrorListener.OnInStreamErrorAsync()
{
this.rawOutputContext.VerifyNotDisposed();
await this.rawOutputContext.TextWriter.FlushAsync()
@@ -190,7 +190,7 @@ private ODataAsynchronousResponseMessage CreateResponseMessageImplementation()
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains an
/// that can be used to write the response.
- private async Task CreateResponseMessageImplementationAsync()
+ private async ValueTask CreateResponseMessageImplementationAsync()
{
var responseMessage = await ODataAsynchronousResponseMessage.CreateMessageForWritingAsync(
rawOutputContext.OutputStream,
@@ -235,7 +235,7 @@ private void WriteInnerEnvelope(ODataAsynchronousResponseMessage responseMessage
///
/// The response message to write the envelope.
/// A task that represents the asynchronous write operation.
- private async Task WriteInnerEnvelopeAsync(ODataAsynchronousResponseMessage responseMessage)
+ private async ValueTask WriteInnerEnvelopeAsync(ODataAsynchronousResponseMessage responseMessage)
{
// Write response line.
string statusMessage = HttpUtils.GetStatusMessage(responseMessage.StatusCode);
diff --git a/src/Microsoft.OData.Core/ODataCollectionReader.cs b/src/Microsoft.OData.Core/ODataCollectionReader.cs
index b2bf48b231..f06b1097f9 100644
--- a/src/Microsoft.OData.Core/ODataCollectionReader.cs
+++ b/src/Microsoft.OData.Core/ODataCollectionReader.cs
@@ -42,6 +42,6 @@ public abstract object Item
/// Asynchronously reads the next item from the message payload.
/// A task that when completed indicates whether more items were read.
- public abstract Task ReadAsync();
+ public abstract ValueTask ReadAsync();
}
}
diff --git a/src/Microsoft.OData.Core/ODataCollectionReaderCore.cs b/src/Microsoft.OData.Core/ODataCollectionReaderCore.cs
index b1cabd52dc..9a647883d1 100644
--- a/src/Microsoft.OData.Core/ODataCollectionReaderCore.cs
+++ b/src/Microsoft.OData.Core/ODataCollectionReaderCore.cs
@@ -151,7 +151,7 @@ public override sealed bool Read()
/// Asynchronously reads the next item from the message payload.
///
/// A task that when completed indicates whether more items were read.
- public override sealed Task ReadAsync()
+ public override sealed ValueTask ReadAsync()
{
this.VerifyCanRead(false);
@@ -228,10 +228,10 @@ protected bool ReadSynchronously()
/// Asynchronously reads the next from the message payload.
///
/// A task that when completed indicates whether more items were read.
- protected virtual Task ReadAsynchronously()
+ protected virtual ValueTask ReadAsynchronously()
{
// Use synchronous read and then return a completed task
- return TaskUtils.GetTaskForSynchronousOperation(this.ReadImplementation);
+ return ValueTask.FromResult(this.ReadImplementation());
}
///
@@ -340,7 +340,7 @@ private T InterceptException(Func action)
/// A task that represents the asynchronous operation.
/// The value of the TResult parameter contains the result of executing the .
///
- private async Task InterceptExceptionAsync(Func> action)
+ private async ValueTask InterceptExceptionAsync(Func> action)
{
try
{
diff --git a/src/Microsoft.OData.Core/ODataCollectionReaderCoreAsync.cs b/src/Microsoft.OData.Core/ODataCollectionReaderCoreAsync.cs
index 7bdaacbdd0..a5d044daf9 100644
--- a/src/Microsoft.OData.Core/ODataCollectionReaderCoreAsync.cs
+++ b/src/Microsoft.OData.Core/ODataCollectionReaderCoreAsync.cs
@@ -36,25 +36,25 @@ protected ODataCollectionReaderCoreAsync(
/// Implementation of the collection reader logic when in state 'Start'.
///
/// Task which returns true if more items can be read from the reader; otherwise false.
- protected abstract Task ReadAtStartImplementationAsync();
+ protected abstract ValueTask ReadAtStartImplementationAsync();
///
/// Implementation of the reader logic when in state 'CollectionStart'.
///
/// Task which returns true if more nodes can be read from the reader; otherwise false.
- protected abstract Task ReadAtCollectionStartImplementationAsync();
+ protected abstract ValueTask ReadAtCollectionStartImplementationAsync();
///
/// Implementation of the reader logic when in state 'Value'.
///
/// Task which returns true if more nodes can be read from the reader; otherwise false.
- protected abstract Task ReadAtValueImplementationAsync();
+ protected abstract ValueTask ReadAtValueImplementationAsync();
///
/// Implementation of the reader logic when in state 'CollectionEnd'.
///
/// Task which should return false since no more nodes can be read from the reader after the collection ends.
- protected abstract Task ReadAtCollectionEndImplementationAsync();
+ protected abstract ValueTask ReadAtCollectionEndImplementationAsync();
///
/// Asynchronously reads the next from the message payload.
@@ -62,7 +62,7 @@ protected ODataCollectionReaderCoreAsync(
/// A task that when completed indicates whether more items were read.
/// The base class already implements this but only for fully synchronous readers, the implementation here
/// allows fully asynchronous readers.
- protected override Task ReadAsynchronously()
+ protected override ValueTask ReadAsynchronously()
{
switch (this.State)
{
@@ -80,7 +80,7 @@ protected override Task ReadAsynchronously()
default:
Debug.Assert(false, "Unsupported collection reader state " + this.State + " detected.");
- return TaskUtils.GetFaultedTask(new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataCollectionReaderCoreAsync_ReadAsynchronously)));
+ return ValueTask.FromException(new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataCollectionReaderCoreAsync_ReadAsynchronously)));
}
}
}
diff --git a/src/Microsoft.OData.Core/ODataCollectionWriter.cs b/src/Microsoft.OData.Core/ODataCollectionWriter.cs
index 1f732f7ed6..7289673c44 100644
--- a/src/Microsoft.OData.Core/ODataCollectionWriter.cs
+++ b/src/Microsoft.OData.Core/ODataCollectionWriter.cs
@@ -23,7 +23,7 @@ public abstract class ODataCollectionWriter
/// Asynchronously start writing a collection.
/// A task instance that represents the asynchronous write operation.
/// The representing the collection.
- public abstract Task WriteStartAsync(ODataCollectionStart collectionStart);
+ public abstract ValueTask WriteStartAsync(ODataCollectionStart collectionStart);
/// Write a collection item.
/// The collection item to write.
@@ -32,14 +32,14 @@ public abstract class ODataCollectionWriter
/// Asynchronously write a collection item.
/// A task instance that represents the asynchronous write operation.
/// The collection item to write.
- public abstract Task WriteItemAsync(object item);
+ public abstract ValueTask WriteItemAsync(object item);
/// Finishes writing a collection.
public abstract void WriteEnd();
/// Asynchronously finish writing a collection.
/// A task instance that represents the asynchronous write operation.
- public abstract Task WriteEndAsync();
+ public abstract ValueTask WriteEndAsync();
/// Flushes the write buffer to the underlying stream.
public abstract void Flush();
diff --git a/src/Microsoft.OData.Core/ODataCollectionWriterCore.cs b/src/Microsoft.OData.Core/ODataCollectionWriterCore.cs
index 7878b5080e..8c420895d9 100644
--- a/src/Microsoft.OData.Core/ODataCollectionWriterCore.cs
+++ b/src/Microsoft.OData.Core/ODataCollectionWriterCore.cs
@@ -178,7 +178,7 @@ public sealed override void WriteStart(ODataCollectionStart collectionStart)
///
/// The representing the collection.
/// A task instance that represents the asynchronous write operation.
- public sealed override Task WriteStartAsync(ODataCollectionStart collection)
+ public sealed override ValueTask WriteStartAsync(ODataCollectionStart collection)
{
this.VerifyCanWriteStart(false, collection);
return this.WriteStartImplementationAsync(collection);
@@ -199,7 +199,7 @@ public sealed override void WriteItem(object item)
///
/// The collection item to write.
/// A task instance that represents the asynchronous write operation.
- public sealed override Task WriteItemAsync(object item)
+ public sealed override ValueTask WriteItemAsync(object item)
{
this.VerifyCanWriteItem(false);
return this.WriteItemImplementationAsync(item);
@@ -224,7 +224,7 @@ public sealed override void WriteEnd()
/// Asynchronously finish writing a collection.
///
/// A task instance that represents the asynchronous write operation.
- public sealed override async Task WriteEndAsync()
+ public sealed override async ValueTask WriteEndAsync()
{
this.VerifyCanWriteEnd(false);
await this.WriteEndImplementationAsync()
@@ -261,7 +261,7 @@ void IODataOutputInStreamErrorListener.OnInStreamError()
}
///
- async Task IODataOutputInStreamErrorListener.OnInStreamErrorAsync()
+ async ValueTask IODataOutputInStreamErrorListener.OnInStreamErrorAsync()
{
this.VerifyNotDisposed();
@@ -336,26 +336,26 @@ protected static bool IsErrorState(CollectionWriterState state)
/// Asynchronously start writing an OData payload.
///
/// A task that represents the asynchronous write operation.
- protected abstract Task StartPayloadAsync();
+ protected abstract ValueTask StartPayloadAsync();
///
/// Asynchronously finish writing an OData payload.
///
/// A task that represents the asynchronous write operation.
- protected abstract Task EndPayloadAsync();
+ protected abstract ValueTask EndPayloadAsync();
///
/// Asynchronously start writing a collection.
///
/// The representing the collection.
/// A task that represents the asynchronous write operation.
- protected abstract Task StartCollectionAsync(ODataCollectionStart collectionStart);
+ protected abstract ValueTask StartCollectionAsync(ODataCollectionStart collectionStart);
///
/// Asynchronously finish writing a collection.
///
/// A task that represents the asynchronous write operation.
- protected abstract Task EndCollectionAsync();
+ protected abstract ValueTask EndCollectionAsync();
///
/// Asynchronously writes a collection item (either primitive or complex)
@@ -363,7 +363,7 @@ protected static bool IsErrorState(CollectionWriterState state)
/// The collection item to write.
/// The expected type of the collection item or null if no expected item type exists.
/// A task that represents the asynchronous write operation.
- protected abstract Task WriteCollectionItemAsync(object item, IEdmTypeReference expectedItemTypeReference);
+ protected abstract ValueTask WriteCollectionItemAsync(object item, IEdmTypeReference expectedItemTypeReference);
///
/// Verifies that calling WriteStart is valid.
@@ -695,7 +695,7 @@ private void ValidateTransition(CollectionWriterState newState)
/// Make sure to only use anonymous functions that don't capture state from the enclosing context,
/// so the compiler optimizes the code to avoid delegate and closure allocations on every call to this method.
///
- private async Task InterceptExceptionAsync(Func action)
+ private async ValueTask InterceptExceptionAsync(Func action)
{
try
{
@@ -723,7 +723,7 @@ private async Task InterceptExceptionAsync(Func
/// Make sure to only use anonymous functions that don't capture state from the enclosing context,
/// so the compiler optimizes the code to avoid delegate and closure allocations on every call to this method.
///
- private async Task InterceptExceptionAsync(Func action, TArg0 arg0)
+ private async ValueTask InterceptExceptionAsync(Func action, TArg0 arg0)
{
try
{
@@ -744,7 +744,7 @@ private async Task InterceptExceptionAsync(Func
/// A task that represents the asynchronous write operation.
- private Task StartPayloadInStartStateAsync()
+ private ValueTask StartPayloadInStartStateAsync()
{
Scope current = this.scopes.Peek();
if (current.State == CollectionWriterState.Start)
@@ -752,7 +752,7 @@ private Task StartPayloadInStartStateAsync()
return this.InterceptExceptionAsync((thisParam) => thisParam.StartPayloadAsync());
}
- return TaskUtils.CompletedTask;
+ return ValueTask.CompletedTask;
}
///
@@ -760,7 +760,7 @@ private Task StartPayloadInStartStateAsync()
///
/// The representing the collection.
/// A task that represents the asynchronous write operation.
- private async Task WriteStartImplementationAsync(ODataCollectionStart collectionStart)
+ private async ValueTask WriteStartImplementationAsync(ODataCollectionStart collectionStart)
{
await this.StartPayloadInStartStateAsync()
.ConfigureAwait(false);
@@ -783,7 +783,7 @@ await thisParam.StartCollectionAsync(collectionStartParam)
/// Asynchronously finishes writing a collection - implementation of the actual functionality.
///
/// A task that represents the asynchronous write operation.
- private Task WriteEndImplementationAsync()
+ private ValueTask WriteEndImplementationAsync()
{
return this.InterceptExceptionAsync(async (thisParam) =>
{
@@ -818,21 +818,21 @@ private Task WriteEndImplementationAsync()
///
/// The collection item to write.
/// A task that represents the asynchronous write operation.
- private async Task WriteItemImplementationAsync(object item)
+ private ValueTask WriteItemImplementationAsync(object item)
{
if (this.scopes.Peek().State != CollectionWriterState.Item)
{
this.EnterScope(CollectionWriterState.Item, item);
}
- await this.InterceptExceptionAsync(
+ return this.InterceptExceptionAsync(
async(thisParam, itemParam) =>
{
ValidationUtils.ValidateCollectionItem(itemParam, true /* isNullable */);
await thisParam.WriteCollectionItemAsync(itemParam, thisParam.expectedItemType)
.ConfigureAwait(false);
},
- item).ConfigureAwait(false);
+ item);
}
///
@@ -841,7 +841,7 @@ await thisParam.WriteCollectionItemAsync(itemParam, thisParam.expectedItemType)
///
/// Note that this method is never called once an error has been written or a fatal exception has been thrown.
/// A task that represents the asynchronous operation.
- private async Task LeaveScopeAsync()
+ private async ValueTask LeaveScopeAsync()
{
Debug.Assert(this.State != CollectionWriterState.Error, "this.State != WriterState.Error");
diff --git a/src/Microsoft.OData.Core/ODataDeltaReader.cs b/src/Microsoft.OData.Core/ODataDeltaReader.cs
index 3347535ce7..99c9d14db0 100644
--- a/src/Microsoft.OData.Core/ODataDeltaReader.cs
+++ b/src/Microsoft.OData.Core/ODataDeltaReader.cs
@@ -39,6 +39,6 @@ public abstract class ODataDeltaReader
/// Asynchronously reads the next from the message payload.
/// A task that when completed indicates whether more items were read.
- public abstract Task ReadAsync();
+ public abstract ValueTask ReadAsync();
}
}
diff --git a/src/Microsoft.OData.Core/ODataDeltaWriter.cs b/src/Microsoft.OData.Core/ODataDeltaWriter.cs
index 38891241ca..fe871b66f4 100644
--- a/src/Microsoft.OData.Core/ODataDeltaWriter.cs
+++ b/src/Microsoft.OData.Core/ODataDeltaWriter.cs
@@ -27,7 +27,7 @@ public abstract class ODataDeltaWriter
///
/// Delta resource set/collection to write.
/// A task instance that represents the asynchronous write operation.
- public abstract Task WriteStartAsync(ODataDeltaResourceSet deltaResourceSet);
+ public abstract ValueTask WriteStartAsync(ODataDeltaResourceSet deltaResourceSet);
///
/// Finish writing a delta resource set.
@@ -38,7 +38,7 @@ public abstract class ODataDeltaWriter
/// Asynchronously finish writing a delta resource set.
///
/// A task instance that represents the asynchronous write operation.
- public abstract Task WriteEndAsync();
+ public abstract ValueTask WriteEndAsync();
///
/// Start writing a nested resource info.
@@ -51,7 +51,7 @@ public abstract class ODataDeltaWriter
///
/// The nested resource info to write.
/// A task instance that represents the asynchronous write operation.
- public abstract Task WriteStartAsync(ODataNestedResourceInfo nestedResourceInfo);
+ public abstract ValueTask WriteStartAsync(ODataNestedResourceInfo nestedResourceInfo);
///
/// Start writing an expanded resource set.
@@ -64,7 +64,7 @@ public abstract class ODataDeltaWriter
///
/// The expanded resource set to write.
/// A task instance that represents the asynchronous write operation.
- public abstract Task WriteStartAsync(ODataResourceSet expandedResourceSet);
+ public abstract ValueTask WriteStartAsync(ODataResourceSet expandedResourceSet);
///
/// Start writing a delta resource.
@@ -77,7 +77,7 @@ public abstract class ODataDeltaWriter
///
/// The delta resource to write.
/// A task instance that represents the asynchronous write operation.
- public abstract Task WriteStartAsync(ODataResource deltaResource);
+ public abstract ValueTask WriteStartAsync(ODataResource deltaResource);
///
@@ -91,7 +91,7 @@ public abstract class ODataDeltaWriter
///
/// The delta deleted resource to write.
/// A task instance that represents the asynchronous write operation.
- public abstract Task WriteDeltaDeletedEntryAsync(ODataDeltaDeletedEntry deltaDeletedEntry);
+ public abstract ValueTask WriteDeltaDeletedEntryAsync(ODataDeltaDeletedEntry deltaDeletedEntry);
///
/// Writing a delta link.
@@ -104,7 +104,7 @@ public abstract class ODataDeltaWriter
///
/// The delta link to write.
/// A task instance that represents the asynchronous write operation.
- public abstract Task WriteDeltaLinkAsync(ODataDeltaLink deltaLink);
+ public abstract ValueTask WriteDeltaLinkAsync(ODataDeltaLink deltaLink);
///
/// Writing a delta deleted link.
@@ -117,7 +117,7 @@ public abstract class ODataDeltaWriter
///
/// The delta deleted link to write.
/// A task instance that represents the asynchronous write operation.
- public abstract Task WriteDeltaDeletedLinkAsync(ODataDeltaDeletedLink deltaDeletedLink);
+ public abstract ValueTask WriteDeltaDeletedLinkAsync(ODataDeltaDeletedLink deltaDeletedLink);
///
/// Flushes the write buffer to the underlying stream.
diff --git a/src/Microsoft.OData.Core/ODataFormat.cs b/src/Microsoft.OData.Core/ODataFormat.cs
index 5c623dc73c..6c29957577 100644
--- a/src/Microsoft.OData.Core/ODataFormat.cs
+++ b/src/Microsoft.OData.Core/ODataFormat.cs
@@ -110,7 +110,7 @@ public static ODataFormat Metadata
/// The stream returned by GetMessageStream of could be used for reading for
/// payload kind detection. Reading this stream won't affect later reading operations of payload processing.
///
- public abstract Task> DetectPayloadKindAsync(ODataMessageInfo messageInfo, ODataMessageReaderSettings settings);
+ public abstract ValueTask> DetectPayloadKindAsync(ODataMessageInfo messageInfo, ODataMessageReaderSettings settings);
///
/// Asynchronously creates an instance of the input context for this format.
@@ -118,7 +118,7 @@ public static ODataFormat Metadata
/// The context information for the message.
/// Configuration settings of the OData reader.
/// Task which when completed returned the newly created input context.
- public abstract Task CreateInputContextAsync(ODataMessageInfo messageInfo, ODataMessageReaderSettings messageReaderSettings);
+ public abstract ValueTask CreateInputContextAsync(ODataMessageInfo messageInfo, ODataMessageReaderSettings messageReaderSettings);
///
/// Creates an instance of the output context for this format.
@@ -126,7 +126,7 @@ public static ODataFormat Metadata
/// The context information for the message.
/// Configuration settings of the OData writer.
/// Task which represents the pending create operation.
- public abstract Task CreateOutputContextAsync(ODataMessageInfo messageInfo, ODataMessageWriterSettings messageWriterSettings);
+ public abstract ValueTask CreateOutputContextAsync(ODataMessageInfo messageInfo, ODataMessageWriterSettings messageWriterSettings);
///
/// Returns the appropriate content-type for this format.
diff --git a/src/Microsoft.OData.Core/ODataInputContext.cs b/src/Microsoft.OData.Core/ODataInputContext.cs
index 8ed1fc6b6a..4b2c9ed8c3 100644
--- a/src/Microsoft.OData.Core/ODataInputContext.cs
+++ b/src/Microsoft.OData.Core/ODataInputContext.cs
@@ -21,7 +21,7 @@ namespace Microsoft.OData
/// Base class for all input contexts, defines the interface
/// to be implemented by the specific formats.
///
- public abstract class ODataInputContext : IDisposable
+ public abstract class ODataInputContext : IDisposable, IAsyncDisposable
{
/// The format for this input context.
private readonly ODataFormat format;
@@ -176,6 +176,19 @@ public void Dispose()
GC.SuppressFinalize(this);
}
+ ///
+ /// IAsyncDisposable.DisposeAsync() implementation to clean up resources of the context
+ /// asynchronously.
+ ///
+ /// A task representing the result of the asynchronous operation.
+ public async ValueTask DisposeAsync()
+ {
+ await this.DisposeAsyncCore();
+ this.Dispose(false);
+
+ GC.SuppressFinalize(this);
+ }
+
///
/// Creates an to read a resource set.
///
@@ -193,7 +206,7 @@ public virtual ODataReader CreateResourceSetReader(IEdmEntitySetBase entitySet,
/// The entity set we are going to read resources for.
/// The expected structured type for the items in the resource set.
/// Task which when completed returns the newly created .
- public virtual Task CreateResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
+ public virtual ValueTask CreateResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.ResourceSet);
}
@@ -215,7 +228,7 @@ public virtual ODataReader CreateDeltaResourceSetReader(IEdmEntitySetBase entity
/// The entity set we are going to read resources for.
/// The expected structured type for the items in the resource set.
/// Task which when completed returns the newly created .
- public virtual Task CreateDeltaResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
+ public virtual ValueTask CreateDeltaResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.ResourceSet);
}
@@ -237,7 +250,7 @@ public virtual ODataReader CreateResourceReader(IEdmNavigationSource navigationS
/// The navigation source we are going to read resources for.
/// The expected structured type for the resource to be read.
/// Task which when completed returns the newly created .
- public virtual Task CreateResourceReaderAsync(IEdmNavigationSource navigationSource, IEdmStructuredType expectedResourceType)
+ public virtual ValueTask CreateResourceReaderAsync(IEdmNavigationSource navigationSource, IEdmStructuredType expectedResourceType)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Resource);
}
@@ -257,7 +270,7 @@ public virtual ODataCollectionReader CreateCollectionReader(IEdmTypeReference ex
///
/// The expected type reference for the items in the collection.
/// Task which when completed returns the newly created .
- public virtual Task CreateCollectionReaderAsync(IEdmTypeReference expectedItemTypeReference)
+ public virtual ValueTask CreateCollectionReaderAsync(IEdmTypeReference expectedItemTypeReference)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Collection);
}
@@ -281,7 +294,7 @@ public virtual ODataProperty ReadProperty(IEdmStructuralProperty edmStructuralPr
/// The producing the property to be read.
/// The expected type reference of the property to read.
/// Task which when completed returns an representing the read property.
- public virtual Task ReadPropertyAsync(IEdmStructuralProperty edmStructuralProperty, IEdmTypeReference expectedPropertyTypeReference)
+ public virtual ValueTask ReadPropertyAsync(IEdmStructuralProperty edmStructuralProperty, IEdmTypeReference expectedPropertyTypeReference)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Property);
}
@@ -299,7 +312,7 @@ public virtual ODataError ReadError()
/// Asynchronously read a top-level error.
///
/// Task which when completed returns an representing the read error.
- public virtual Task ReadErrorAsync()
+ public virtual ValueTask ReadErrorAsync()
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Error);
}
@@ -321,7 +334,7 @@ public virtual ODataReader CreateUriParameterResourceReader(IEdmNavigationSource
/// The navigation source we are going to read resources for.
/// The expected structured type for the resource to be read.
/// Task which when completed returns the newly created .
- public virtual Task CreateUriParameterResourceReaderAsync(IEdmNavigationSource navigationSource, IEdmStructuredType expectedResourceType)
+ public virtual ValueTask CreateUriParameterResourceReaderAsync(IEdmNavigationSource navigationSource, IEdmStructuredType expectedResourceType)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Parameter);
}
@@ -343,7 +356,7 @@ public virtual ODataReader CreateUriParameterResourceSetReader(IEdmEntitySetBase
/// The entity set we are going to read resources for.
/// The expected structured type for the items in the resource set.
/// Task which when completed returns the newly created .
- public virtual Task CreateUriParameterResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
+ public virtual ValueTask CreateUriParameterResourceSetReaderAsync(IEdmEntitySetBase entitySet, IEdmStructuredType expectedResourceType)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.ResourceSet);
}
@@ -363,7 +376,7 @@ public virtual ODataParameterReader CreateParameterReader(IEdmOperation operatio
///
/// The operation whose parameters are being read.
/// Task which when completed returns the newly created .
- public virtual Task CreateParameterReaderAsync(IEdmOperation operation)
+ public virtual ValueTask CreateParameterReaderAsync(IEdmOperation operation)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Parameter);
}
@@ -381,7 +394,7 @@ internal virtual ODataAsynchronousReader CreateAsynchronousReader()
/// Asynchronously create an .
///
/// Task which when completed returns the newly created .
- internal virtual Task CreateAsynchronousReaderAsync()
+ internal virtual ValueTask CreateAsynchronousReaderAsync()
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Asynchronous);
}
@@ -403,7 +416,7 @@ internal virtual ODataDeltaReader CreateDeltaReader(IEdmEntitySetBase entitySet,
/// The entity set we are going to read entities for.
/// The expected base entity type for the entries in the delta response.
/// Task which when completed returns the newly created .
- internal virtual Task CreateDeltaReaderAsync(IEdmEntitySetBase entitySet, IEdmEntityType expectedBaseEntityType)
+ internal virtual ValueTask CreateDeltaReaderAsync(IEdmEntitySetBase entitySet, IEdmEntityType expectedBaseEntityType)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.ResourceSet);
}
@@ -427,7 +440,7 @@ internal virtual ODataBatchReader CreateBatchReader()
///
/// Since we don't want to support batch format extensibility (at least not yet) this method should remain internal.
///
- internal virtual Task CreateBatchReaderAsync()
+ internal virtual ValueTask CreateBatchReaderAsync()
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Batch);
}
@@ -449,7 +462,7 @@ internal virtual ODataServiceDocument ReadServiceDocument()
/// an that represents the read service document.
///
/// Task which when completed returns an representing the read service document.
- internal virtual Task ReadServiceDocumentAsync()
+ internal virtual ValueTask ReadServiceDocumentAsync()
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.ServiceDocument);
}
@@ -502,7 +515,7 @@ internal virtual ODataEntityReferenceLinks ReadEntityReferenceLinks()
/// Asynchronously read a set of top-level entity reference links.
///
/// Task which when completed returns an representing the read links.
- internal virtual Task ReadEntityReferenceLinksAsync()
+ internal virtual ValueTask ReadEntityReferenceLinksAsync()
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.EntityReferenceLinks);
}
@@ -520,7 +533,7 @@ internal virtual ODataEntityReferenceLink ReadEntityReferenceLink()
/// Asynchronously read a top-level entity reference link.
///
/// Task which when completed returns an representing the read entity reference link.
- internal virtual Task ReadEntityReferenceLinkAsync()
+ internal virtual ValueTask ReadEntityReferenceLinkAsync()
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.EntityReferenceLink);
}
@@ -540,7 +553,7 @@ internal virtual object ReadValue(IEdmPrimitiveTypeReference expectedPrimitiveTy
///
/// The expected type reference for the value to be read; null if no expected type is available.
/// Task which when completed returns an representing the read value.
- internal virtual Task ReadValueAsync(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
+ internal virtual ValueTask ReadValueAsync(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
{
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Value);
}
@@ -627,6 +640,16 @@ protected virtual void Dispose(bool disposing)
this.disposed = true;
}
+ ///
+ /// Perform the actual cleanup work asynchronously.
+ ///
+ /// A task representing the result of the asynchronous operation.
+ protected virtual ValueTask DisposeAsyncCore()
+ {
+ this.disposed = true;
+ return ValueTask.CompletedTask;
+ }
+
///
/// Creates an exception which reports that the specified payload kind if not support by this format.
///
diff --git a/src/Microsoft.OData.Core/ODataMessage.cs b/src/Microsoft.OData.Core/ODataMessage.cs
index 9b0eccb924..5520731db4 100644
--- a/src/Microsoft.OData.Core/ODataMessage.cs
+++ b/src/Microsoft.OData.Core/ODataMessage.cs
@@ -113,7 +113,7 @@ protected internal bool? UseBufferingReadStream
///
/// The stream for this message.
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Intentionally a method.")]
- public abstract Task GetStreamAsync();
+ public abstract ValueTask GetStreamAsync();
///
/// Queries the message for the specified interface type.
@@ -180,7 +180,7 @@ protected internal Stream GetStream(Func messageStreamFunc, bool isReque
/// A function that returns a task for the stream backing the message.
/// true if the message is a request message; false for a response message.
/// A task that when completed returns the stream backing the message.
- protected internal Task GetStreamAsync(Func> streamFuncAsync, bool isRequest)
+ protected internal ValueTask GetStreamAsync(Func> streamFuncAsync, bool isRequest)
{
// Check whether we have an existing buffering read stream when reading
if (!this.writing)
@@ -190,16 +190,15 @@ protected internal Task GetStreamAsync(Func> streamFuncAsyn
if (existingBufferingReadStream != null)
{
Debug.Assert(this.useBufferingReadStream.HasValue, "UseBufferingReadStream must have been set.");
- return Task.FromResult(existingBufferingReadStream);
+ return ValueTask.FromResult(existingBufferingReadStream);
}
}
return GetMessageStreamAsync(streamFuncAsync, isRequest);
- async Task GetMessageStreamAsync(Func> innerStreamFuncAsync, bool innerIsRequest)
+ async ValueTask GetMessageStreamAsync(Func> innerStreamFuncAsync, bool innerIsRequest)
{
- Task messageStreamTask = innerStreamFuncAsync();
- ValidateMessageStreamTask(messageStreamTask, innerIsRequest);
+ ValueTask messageStreamTask = innerStreamFuncAsync();
// Wrap it in a non-disposing stream if requested
Stream messageStream = await messageStreamTask
@@ -274,22 +273,6 @@ private static void ValidateMessageStream(Stream stream, bool isRequest)
}
}
- ///
- /// Validates that a given task providing the message stream can be used.
- ///
- /// The task to validate.
- /// true if the message is a request message; false for a response message.
- private static void ValidateMessageStreamTask(Task streamTask, bool isRequest)
- {
- if (streamTask == null)
- {
- string error = isRequest
- ? Strings.ODataRequestMessage_StreamTaskIsNull
- : Strings.ODataResponseMessage_StreamTaskIsNull;
- throw new ODataException(error);
- }
- }
-
///
/// Gets the buffering read stream if one is available; otherwise returns null.
///
diff --git a/src/Microsoft.OData.Core/ODataMessageReader.cs b/src/Microsoft.OData.Core/ODataMessageReader.cs
index 5b66f67bdb..49f905ee10 100644
--- a/src/Microsoft.OData.Core/ODataMessageReader.cs
+++ b/src/Microsoft.OData.Core/ODataMessageReader.cs
@@ -256,34 +256,32 @@ public IEnumerable DetectPayloadKind()
/// will always at most return a single result per payload kind.
///
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Need to a return a task of an enumerable.")]
- public Task> DetectPayloadKindAsync()
+ public async ValueTask> DetectPayloadKindAsync()
{
IEnumerable payloadKindsFromContentType;
if (this.TryGetSinglePayloadKindResultFromContentType(out payloadKindsFromContentType))
{
- return Task.FromResult(payloadKindsFromContentType);
+ return payloadKindsFromContentType;
}
// Otherwise we have to do sniffing
List detectedPayloadKinds = new List();
- // NOTE: this relies on the lazy eval of the enumerator
- return Task.Factory.Iterate(this.GetPayloadKindDetectionTasks(payloadKindsFromContentType, detectedPayloadKinds))
- .FollowAlwaysWith(
- t =>
- {
- // We are done sniffing; stop buffering.
- this.message.UseBufferingReadStream = false;
- this.message.BufferingReadStream.StopBuffering();
- })
- .FollowOnSuccessWith(
- t =>
- {
- // Always sort by payload kind to guarantee stable order of results in case clients rely on it
- detectedPayloadKinds.Sort(this.ComparePayloadKindDetectionResult);
+ try
+ {
+ await this.GetPayloadKindDetectionTasks(payloadKindsFromContentType, detectedPayloadKinds)
+ .ConfigureAwait(false);
+ // Always sort by payload kind to guarantee stable order of results in case clients rely on it
+ detectedPayloadKinds.Sort(this.ComparePayloadKindDetectionResult);
- return (IEnumerable)detectedPayloadKinds;
- });
+ return detectedPayloadKinds;
+ }
+ finally
+ {
+ // We are done sniffing; stop buffering.
+ this.message.UseBufferingReadStream = false;
+ this.message.BufferingReadStream.StopBuffering();
+ }
}
/// Creates an