diff --git a/xml/Microsoft.Extensions.Caching.Distributed/DistributedCacheExtensions.xml b/xml/Microsoft.Extensions.Caching.Distributed/DistributedCacheExtensions.xml index 8a4719cc0ac..52de3c66bc1 100644 --- a/xml/Microsoft.Extensions.Caching.Distributed/DistributedCacheExtensions.xml +++ b/xml/Microsoft.Extensions.Caching.Distributed/DistributedCacheExtensions.xml @@ -132,6 +132,7 @@ Asynchronously gets a string from the specified cache with the specified key. A task that gets the string value from the stored cache key. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -242,6 +243,7 @@ This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . or is null. + The cancellation token was canceled. This exception is stored into the returned task. @@ -427,6 +429,7 @@ This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . or is null. + The cancellation token was canceled. This exception is stored into the returned task. @@ -468,6 +471,7 @@ This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . or is null. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Caching.Distributed/IDistributedCache.xml b/xml/Microsoft.Extensions.Caching.Distributed/IDistributedCache.xml index 2eda84248d1..067c9c98b32 100644 --- a/xml/Microsoft.Extensions.Caching.Distributed/IDistributedCache.xml +++ b/xml/Microsoft.Extensions.Caching.Distributed/IDistributedCache.xml @@ -117,6 +117,7 @@ Gets a value with the given key. The that represents the asynchronous operation, containing the located value or null. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -209,6 +210,7 @@ Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any). The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -301,6 +303,7 @@ Removes the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -405,6 +408,7 @@ Sets the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Caching.Distributed/MemoryDistributedCache.xml b/xml/Microsoft.Extensions.Caching.Distributed/MemoryDistributedCache.xml index 222609a8eba..88cdaf80a05 100644 --- a/xml/Microsoft.Extensions.Caching.Distributed/MemoryDistributedCache.xml +++ b/xml/Microsoft.Extensions.Caching.Distributed/MemoryDistributedCache.xml @@ -210,6 +210,7 @@ Gets a value with the given key. The that represents the asynchronous operation, containing the located value or . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -311,6 +312,7 @@ Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any). The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -412,6 +414,7 @@ Removes the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -525,6 +528,7 @@ Sets the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Caching.Redis/RedisCache.xml b/xml/Microsoft.Extensions.Caching.Redis/RedisCache.xml index f03fc5b692e..3fc7650055a 100644 --- a/xml/Microsoft.Extensions.Caching.Redis/RedisCache.xml +++ b/xml/Microsoft.Extensions.Caching.Redis/RedisCache.xml @@ -172,6 +172,7 @@ Gets a value with the given key. The that represents the asynchronous operation, containing the located value or . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -263,6 +264,7 @@ Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any). The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -354,6 +356,7 @@ Removes the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -457,6 +460,7 @@ Sets the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Caching.SqlServer/SqlServerCache.xml b/xml/Microsoft.Extensions.Caching.SqlServer/SqlServerCache.xml index d54b0b0a2f3..1a8eb1e4bb2 100644 --- a/xml/Microsoft.Extensions.Caching.SqlServer/SqlServerCache.xml +++ b/xml/Microsoft.Extensions.Caching.SqlServer/SqlServerCache.xml @@ -149,6 +149,7 @@ Gets a value with the given key. The that represents the asynchronous operation, containing the located value or . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -244,6 +245,7 @@ Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any). The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -339,6 +341,7 @@ Removes the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -446,6 +449,7 @@ Sets the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Caching.StackExchangeRedis/RedisCache.xml b/xml/Microsoft.Extensions.Caching.StackExchangeRedis/RedisCache.xml index 558e1a5ecb6..32a31b304df 100644 --- a/xml/Microsoft.Extensions.Caching.StackExchangeRedis/RedisCache.xml +++ b/xml/Microsoft.Extensions.Caching.StackExchangeRedis/RedisCache.xml @@ -135,6 +135,7 @@ Gets a value with the given key. The that represents the asynchronous operation, containing the located value or . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -195,6 +196,7 @@ Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any). The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -255,6 +257,7 @@ Removes the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -323,6 +326,7 @@ Sets the value with the given key. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Diagnostics.HealthChecks/HealthCheckService.xml b/xml/Microsoft.Extensions.Diagnostics.HealthChecks/HealthCheckService.xml index 6590fec31fe..1d82d15e560 100644 --- a/xml/Microsoft.Extensions.Diagnostics.HealthChecks/HealthCheckService.xml +++ b/xml/Microsoft.Extensions.Diagnostics.HealthChecks/HealthCheckService.xml @@ -19,16 +19,16 @@ - A service which can be used to check the status of instances + A service which can be used to check the status of instances registered in the application. The default implementation of is registered in the dependency - injection container as a singleton service by calling + injection container as a singleton service by calling . - The returned by + The returned by provides a convenience API for registering health checks. @@ -91,6 +91,7 @@ yielding a containing the results. . To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -128,6 +129,7 @@ yielding a containing the results. . To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Diagnostics.HealthChecks/IHealthCheck.xml b/xml/Microsoft.Extensions.Diagnostics.HealthChecks/IHealthCheck.xml index bea26e11d6f..b98924dcfca 100644 --- a/xml/Microsoft.Extensions.Diagnostics.HealthChecks/IHealthCheck.xml +++ b/xml/Microsoft.Extensions.Diagnostics.HealthChecks/IHealthCheck.xml @@ -50,6 +50,7 @@ Runs the health check, returning the status of the component being checked. A that completes when the health check has finished, yielding the status of the component being checked. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Diagnostics.HealthChecks/IHealthCheckPublisher.xml b/xml/Microsoft.Extensions.Diagnostics.HealthChecks/IHealthCheckPublisher.xml index a76c26e6364..8f7e3195d72 100644 --- a/xml/Microsoft.Extensions.Diagnostics.HealthChecks/IHealthCheckPublisher.xml +++ b/xml/Microsoft.Extensions.Diagnostics.HealthChecks/IHealthCheckPublisher.xml @@ -66,6 +66,7 @@ Publishes the provided . A which will complete when publishing is complete. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Hosting.Internal/ConsoleLifetime.xml b/xml/Microsoft.Extensions.Hosting.Internal/ConsoleLifetime.xml index ce326d954fb..bc30d3c9109 100644 --- a/xml/Microsoft.Extensions.Hosting.Internal/ConsoleLifetime.xml +++ b/xml/Microsoft.Extensions.Hosting.Internal/ConsoleLifetime.xml @@ -225,6 +225,7 @@ This API supports the .NET infrastructure and is not intended to be used directl ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -267,6 +268,7 @@ This API supports the .NET infrastructure and is not intended to be used directl ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Hosting.Systemd/SystemdLifetime.xml b/xml/Microsoft.Extensions.Hosting.Systemd/SystemdLifetime.xml index b15e98885c6..69f9c2b956b 100644 --- a/xml/Microsoft.Extensions.Hosting.Systemd/SystemdLifetime.xml +++ b/xml/Microsoft.Extensions.Hosting.Systemd/SystemdLifetime.xml @@ -106,6 +106,7 @@ Asynchronously stops and shuts down the host. This method is called from . A task that represents the asynchronous stop operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -135,6 +136,7 @@ Asynchronously waits until the start operation is complete before continuing. This method is called at the beginning of . This can be used to delay startup until signaled by an external event. A task that represents the waiting for start operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Hosting.WindowsServices/WindowsServiceLifetime.xml b/xml/Microsoft.Extensions.Hosting.WindowsServices/WindowsServiceLifetime.xml index 11fb4c74bfe..be231fd8ee7 100644 --- a/xml/Microsoft.Extensions.Hosting.WindowsServices/WindowsServiceLifetime.xml +++ b/xml/Microsoft.Extensions.Hosting.WindowsServices/WindowsServiceLifetime.xml @@ -150,6 +150,7 @@ Asynchronously stops and shuts down the host. This method is called from . A task that represents the asynchronous stop operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -179,6 +180,7 @@ Asynchronously waits until start is complete before continuing. This method is called at the beginning of . This can be used to delay startup until signaled by an external event. A task that represents the asynchronous waiting for start operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Hosting/BackgroundService.xml b/xml/Microsoft.Extensions.Hosting/BackgroundService.xml index 74cda548ba3..ad7291b6b56 100644 --- a/xml/Microsoft.Extensions.Hosting/BackgroundService.xml +++ b/xml/Microsoft.Extensions.Hosting/BackgroundService.xml @@ -122,6 +122,7 @@ For implementation guidelines, see [Worker Services in .NET](/dotnet/core/extens ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -187,6 +188,7 @@ Will return `null` if the background operation hasn't started. Triggered when the application host is ready to start the service. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -227,6 +229,7 @@ Will return `null` if the background operation hasn't started. Triggered when the application host is performing a graceful shutdown. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Hosting/HostingAbstractionsHostBuilderExtensions.xml b/xml/Microsoft.Extensions.Hosting/HostingAbstractionsHostBuilderExtensions.xml index c9df69bb2e5..4a5a0f6852d 100644 --- a/xml/Microsoft.Extensions.Hosting/HostingAbstractionsHostBuilderExtensions.xml +++ b/xml/Microsoft.Extensions.Hosting/HostingAbstractionsHostBuilderExtensions.xml @@ -89,6 +89,7 @@ Builds and starts the host. The started . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Hosting/HostingAbstractionsHostExtensions.xml b/xml/Microsoft.Extensions.Hosting/HostingAbstractionsHostExtensions.xml index de1934c51ca..b5ff0559597 100644 --- a/xml/Microsoft.Extensions.Hosting/HostingAbstractionsHostExtensions.xml +++ b/xml/Microsoft.Extensions.Hosting/HostingAbstractionsHostExtensions.xml @@ -90,6 +90,7 @@ Runs an application and returns a Task that only completes when the token is triggered or shutdown is triggered and all instances are stopped. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -222,6 +223,7 @@ Returns a Task that completes when shutdown is triggered via the given token. The that represents the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Hosting/HostingHostBuilderExtensions.xml b/xml/Microsoft.Extensions.Hosting/HostingHostBuilderExtensions.xml index 71d84f59499..b9f637331fc 100644 --- a/xml/Microsoft.Extensions.Hosting/HostingHostBuilderExtensions.xml +++ b/xml/Microsoft.Extensions.Hosting/HostingHostBuilderExtensions.xml @@ -14,13 +14,24 @@ 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 System.Object + + + [System.Runtime.CompilerServices.Nullable(0)] + [<System.Runtime.CompilerServices.Nullable(0)>] + + + [System.Runtime.CompilerServices.NullableContext(1)] + [<System.Runtime.CompilerServices.NullableContext(1)>] + + - To be added. + Provides extension methods for the from the hosting package. To be added. @@ -41,6 +52,7 @@ 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 Microsoft.Extensions.Hosting.IHostBuilder @@ -77,20 +89,27 @@ 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 Microsoft.Extensions.Hosting.IHostBuilder - + + + + [System.Runtime.CompilerServices.Nullable(2)] + [<System.Runtime.CompilerServices.Nullable(2)>] + + + - - + The type of the builder. The to configure. The delegate for configuring the . Enables configuring the instantiated dependency container. This can be called multiple times and @@ -106,12 +125,13 @@ - + Method Microsoft.Extensions.Hosting 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -123,8 +143,15 @@ Microsoft.Extensions.Hosting.IHostBuilder - - + + + + + [System.Runtime.CompilerServices.Nullable(new System.Byte[] { 2, 1 })] + [<System.Runtime.CompilerServices.Nullable(new System.Byte[] { 2, 1 })>] + + + The existing builder to configure. @@ -163,13 +190,14 @@ The following defaults are applied to the Microsoft.Extensions.Hosting 6.0.0.0 7.0.0.0 + 8.0.0.0 Microsoft.Extensions.Hosting.IHostBuilder - - + + The to configure. @@ -191,13 +219,14 @@ The following defaults are applied to the Microsoft.Extensions.Hosting 6.0.0.0 7.0.0.0 + 8.0.0.0 Microsoft.Extensions.Hosting.IHostBuilder - - + + The to configure. @@ -224,6 +253,7 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 Microsoft.Extensions.Hosting.IHostBuilder @@ -257,6 +287,7 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 Microsoft.Extensions.Hosting.IHostBuilder @@ -273,6 +304,60 @@ The following defaults are applied to the To be added. + + + + + + + + Method + + Microsoft.Extensions.Hosting + 8.0.0.0 + + + Microsoft.Extensions.Hosting.IHostBuilder + + + + + + + The to configure. + The delegate that configures the . + Adds a delegate for configuring the provided . This may be called multiple times. + The same instance of the for chaining. + To be added. + + + + + + + + + + Method + + Microsoft.Extensions.Hosting + 8.0.0.0 + + + Microsoft.Extensions.Hosting.IHostBuilder + + + + + + + The to configure. + The delegate that configures the . + Adds a delegate for configuring the provided . This may be called multiple times. + The same instance of the for chaining. + To be added. + + @@ -290,6 +375,7 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 Microsoft.Extensions.Hosting.IHostBuilder @@ -322,21 +408,22 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 - + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] [<System.Runtime.Versioning.UnsupportedOSPlatform("android")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] [<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("ios")] [<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("tvos")] [<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>] @@ -354,6 +441,7 @@ The following defaults are applied to the Enables console support, builds and starts the host, and waits for Ctrl+C or SIGTERM to shut down. A that only completes when the token is signaled or application is shutdown. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -370,21 +458,22 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 - + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] [<System.Runtime.Versioning.UnsupportedOSPlatform("android")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] [<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("ios")] [<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("tvos")] [<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>] @@ -393,9 +482,9 @@ The following defaults are applied to the System.Threading.Tasks.Task - - - + + + The to configure. @@ -404,6 +493,7 @@ The following defaults are applied to the Enables console support, builds and starts the host, and waits for Ctrl+C or SIGTERM to shut down. A that only completes when the token is signaled or application is shutdown. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -423,21 +513,22 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 - + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] [<System.Runtime.Versioning.UnsupportedOSPlatform("android")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] [<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("ios")] [<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("tvos")] [<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>] @@ -471,21 +562,22 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 - + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] [<System.Runtime.Versioning.UnsupportedOSPlatform("android")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] [<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("ios")] [<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("tvos")] [<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>] @@ -494,8 +586,8 @@ The following defaults are applied to the Microsoft.Extensions.Hosting.IHostBuilder - - + + The to configure. @@ -523,6 +615,7 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 Microsoft.Extensions.Hosting.IHostBuilder @@ -534,7 +627,7 @@ The following defaults are applied to the The to configure. Path to root directory of the application. - Specify the content root directory to be used by the host. + Specifies the content root directory to be used by the host. The . To be added. @@ -554,6 +647,7 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -565,14 +659,13 @@ The following defaults are applied to the Microsoft.Extensions.Hosting.IHostBuilder - - + + The to configure. - - - Specify the to be the default one. + The delegate that configures the . + Specifies the to be the default one. The . To be added. @@ -592,6 +685,7 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -603,13 +697,13 @@ The following defaults are applied to the Microsoft.Extensions.Hosting.IHostBuilder - - + + The to configure. The delegate that configures the . - Specify the to be the default one. + Specifies the to be the default one. The . To be added. @@ -631,6 +725,7 @@ The following defaults are applied to the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 Microsoft.Extensions.Hosting.IHostBuilder @@ -642,7 +737,7 @@ The following defaults are applied to the The to configure. The environment to host the application in. - Specify the environment to be used by the host. + Specifies the environment to be used by the host. The . To be added. diff --git a/xml/Microsoft.Extensions.Hosting/IHost.xml b/xml/Microsoft.Extensions.Hosting/IHost.xml index fd0d675509f..b4283920dc0 100644 --- a/xml/Microsoft.Extensions.Hosting/IHost.xml +++ b/xml/Microsoft.Extensions.Hosting/IHost.xml @@ -80,6 +80,7 @@ Starts the program. A that will be completed when the starts. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -110,6 +111,7 @@ Attempts to gracefully stop the program. A that will be completed when the stops. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Hosting/IHostLifetime.xml b/xml/Microsoft.Extensions.Hosting/IHostLifetime.xml index f0e04c39a54..8dbf7f63d65 100644 --- a/xml/Microsoft.Extensions.Hosting/IHostLifetime.xml +++ b/xml/Microsoft.Extensions.Hosting/IHostLifetime.xml @@ -50,6 +50,7 @@ Called from to indicate that the host is stopping and it's time to shut down. A . To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -82,6 +83,7 @@ continuing. This can be used to delay startup until signaled by an external event. A . To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Hosting/IHostedService.xml b/xml/Microsoft.Extensions.Hosting/IHostedService.xml index 6b3ae608e13..dcbd372f906 100644 --- a/xml/Microsoft.Extensions.Hosting/IHostedService.xml +++ b/xml/Microsoft.Extensions.Hosting/IHostedService.xml @@ -52,6 +52,7 @@ Triggered when the application host is ready to start the service. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -84,6 +85,7 @@ Triggered when the application host is performing a graceful shutdown. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Http.Logging/LoggingHttpMessageHandler.xml b/xml/Microsoft.Extensions.Http.Logging/LoggingHttpMessageHandler.xml index 37fdff5c57e..8e5b37f9743 100644 --- a/xml/Microsoft.Extensions.Http.Logging/LoggingHttpMessageHandler.xml +++ b/xml/Microsoft.Extensions.Http.Logging/LoggingHttpMessageHandler.xml @@ -126,6 +126,7 @@ Logs the request and response from the sent + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Http.Logging/LoggingScopeHttpMessageHandler.xml b/xml/Microsoft.Extensions.Http.Logging/LoggingScopeHttpMessageHandler.xml index c46f0668806..d746a2a3bfb 100644 --- a/xml/Microsoft.Extensions.Http.Logging/LoggingScopeHttpMessageHandler.xml +++ b/xml/Microsoft.Extensions.Http.Logging/LoggingScopeHttpMessageHandler.xml @@ -126,6 +126,7 @@ Logs the request and response from the sent + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Http/PolicyHttpMessageHandler.xml b/xml/Microsoft.Extensions.Http/PolicyHttpMessageHandler.xml index 36a02583875..59b452145b1 100644 --- a/xml/Microsoft.Extensions.Http/PolicyHttpMessageHandler.xml +++ b/xml/Microsoft.Extensions.Http/PolicyHttpMessageHandler.xml @@ -32,7 +32,7 @@ The and the convenience methods only accept the generic . Generic policy instances can be created by using the generic methods on such as . To adapt an existing non-generic , use code like the following: - + ``` policy.AsAsyncPolicy<HttpResponseMessage>() ``` @@ -130,6 +130,7 @@ Executes request processing surrounded by a . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -161,6 +162,7 @@ Executes request processing surrounded by a . Called inside the execution of the to perform request processing. Returns a that will yield a response when completed. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BatchingLoggerProvider.xml b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BatchingLoggerProvider.xml index c59425a5b9b..0f21aaa0ec6 100644 --- a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BatchingLoggerProvider.xml +++ b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BatchingLoggerProvider.xml @@ -133,6 +133,7 @@ To be added. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -185,6 +186,7 @@ To be added. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BlobAppendReferenceWrapper.xml b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BlobAppendReferenceWrapper.xml index b10c9f94719..23b95a26121 100644 --- a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BlobAppendReferenceWrapper.xml +++ b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BlobAppendReferenceWrapper.xml @@ -121,6 +121,7 @@ This API supports the .NET infrastructure and is not intended to be used directl ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BlobLoggerProvider.xml b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BlobLoggerProvider.xml index 46aa3276037..e909f07f6ff 100644 --- a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BlobLoggerProvider.xml +++ b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/BlobLoggerProvider.xml @@ -44,8 +44,7 @@ - - + Creates a new instance of . To be added. @@ -69,8 +68,7 @@ - - + The container to store logs to. Creates a new instance of . To be added. @@ -103,6 +101,7 @@ To be added. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/FileLoggerProvider.xml b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/FileLoggerProvider.xml index 3b249d72d80..a731aa82e03 100644 --- a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/FileLoggerProvider.xml +++ b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/FileLoggerProvider.xml @@ -209,6 +209,7 @@ This API supports the .NET infrastructure and is not intended to be used directl This API supports the .NET infrastructure and is not intended to be used directly from your code. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/ICloudAppendBlob.xml b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/ICloudAppendBlob.xml index ee3c9e476bc..8dc37522da7 100644 --- a/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/ICloudAppendBlob.xml +++ b/xml/Microsoft.Extensions.Logging.AzureAppServices.Internal/ICloudAppendBlob.xml @@ -61,6 +61,7 @@ This API supports the .NET infrastructure and is not intended to be used directl ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Logging.AzureAppServices/BatchingLoggerProvider.xml b/xml/Microsoft.Extensions.Logging.AzureAppServices/BatchingLoggerProvider.xml index e01dd65d789..06c39ab4f1d 100644 --- a/xml/Microsoft.Extensions.Logging.AzureAppServices/BatchingLoggerProvider.xml +++ b/xml/Microsoft.Extensions.Logging.AzureAppServices/BatchingLoggerProvider.xml @@ -109,6 +109,7 @@ Wait for the given . A which completes when the has passed or the has been canceled. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/Microsoft.Extensions.Primitives/CancellationChangeToken.xml b/xml/Microsoft.Extensions.Primitives/CancellationChangeToken.xml index 91a1d143687..7645f40595a 100644 --- a/xml/Microsoft.Extensions.Primitives/CancellationChangeToken.xml +++ b/xml/Microsoft.Extensions.Primitives/CancellationChangeToken.xml @@ -59,6 +59,7 @@ The . Initializes a new instance of . To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.CodeDom.Compiler/IndentedTextWriter.xml b/xml/System.CodeDom.Compiler/IndentedTextWriter.xml index c24475c5a87..6c06f596e0b 100644 --- a/xml/System.CodeDom.Compiler/IndentedTextWriter.xml +++ b/xml/System.CodeDom.Compiler/IndentedTextWriter.xml @@ -53,25 +53,25 @@ Provides a text writer that can indent new lines by a tab string token. - extends a by providing methods that insert a tab string and track the current indentation level. Text formatted with multiple indentation levels is useful for generated code, so this class is used by CodeDOM code generator implementations. - - The tab string is the string that each indentation consists of. Typically the tab string contains white space. - + extends a by providing methods that insert a tab string and track the current indentation level. Text formatted with multiple indentation levels is useful for generated code, so this class is used by CodeDOM code generator implementations. + + The tab string is the string that each indentation consists of. Typically the tab string contains white space. + > [!NOTE] -> This class contains a link demand and an inheritance demand at the class level that applies to all members. A is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see [Link Demands](/dotnet/framework/misc/link-demands) and [Inheritance Demands](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/x4yx82e6(v=vs.100)). - - - -## Examples - The following code example demonstrates using an to write text at different levels of indentation. - +> This class contains a link demand and an inheritance demand at the class level that applies to all members. A is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see [Link Demands](/dotnet/framework/misc/link-demands) and [Inheritance Demands](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/x4yx82e6(v=vs.100)). + + + +## Examples + The following code example demonstrates using an to write text at different levels of indentation. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/IndentedTextWriterExample/CPP/form1.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.CodeDom.Compiler/IndentedTextWriter/Overview/form1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IndentedTextWriterExample/VB/form1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IndentedTextWriterExample/VB/form1.vb" id="Snippet1"::: + ]]> @@ -181,15 +181,15 @@ The tab string to use for indentation. Initializes a new instance of the class using the specified text writer and tab string. - using a specified tab string. - + using a specified tab string. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/IndentedTextWriterExample/CPP/form1.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.CodeDom.Compiler/IndentedTextWriter/Overview/form1.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IndentedTextWriterExample/VB/form1.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IndentedTextWriterExample/VB/form1.vb" id="Snippet3"::: + ]]> @@ -280,11 +280,11 @@ Specifies the default tab string. This field is constant. - @@ -408,11 +408,11 @@ Flushes the stream. - @@ -498,15 +498,15 @@ Gets or sets the number of spaces to indent. The number of spaces to indent. - . The indentation level is the number of tab strings to prefix each line with. - + . The indentation level is the number of tab strings to prefix each line with. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/IndentedTextWriterExample/CPP/form1.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.CodeDom.Compiler/IndentedTextWriter/Overview/form1.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IndentedTextWriterExample/VB/form1.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IndentedTextWriterExample/VB/form1.vb" id="Snippet3"::: + ]]> @@ -1452,6 +1452,7 @@ Asynchronously writes the specified characters to the underlying , inserting tabs at the start of every line. A representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1488,6 +1489,7 @@ Asynchronously writes the contents of the specified to the underlying , inserting tabs at the start of every line. A representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2430,6 +2432,7 @@ Asynchronously writes the specified characters followed by a line terminator to the underlying , inserting tabs at the start of every line. A representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2466,6 +2469,7 @@ Asynchronously writes the contents of the specified followed by a line terminator to the underlying , inserting tabs at the start of every line. A representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2553,15 +2557,15 @@ The string to write. Writes the specified string to a line without tabs. - diff --git a/xml/System.Collections.Generic/IAsyncEnumerable`1.xml b/xml/System.Collections.Generic/IAsyncEnumerable`1.xml index 6f6aa76ed61..f8ed2ee6bb1 100644 --- a/xml/System.Collections.Generic/IAsyncEnumerable`1.xml +++ b/xml/System.Collections.Generic/IAsyncEnumerable`1.xml @@ -75,6 +75,7 @@ Returns an enumerator that iterates asynchronously through the collection. An enumerator that can be used to iterate asynchronously through the collection. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Data.Common/DbBatch.xml b/xml/System.Data.Common/DbBatch.xml index 4fd6e4edcbd..4d61fc4d6fd 100644 --- a/xml/System.Data.Common/DbBatch.xml +++ b/xml/System.Data.Common/DbBatch.xml @@ -24,12 +24,12 @@ Represents a batch of commands which can be executed against a data source in a single round trip. Provides a base class for database-specific classes that represent command batches. - @@ -94,11 +94,11 @@ The precise semantics of batch execution vary across ADO.NET providers, especial Attempts to cancel the execution of a . - @@ -286,11 +286,11 @@ The precise semantics of batch execution vary across ADO.NET providers, especial Asynchronously diposes the batch object. A representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . @@ -323,11 +323,11 @@ The precise semantics of batch execution vary across ADO.NET providers, especial When overridden in a derived class, executes the batch against its connection, returning a which can be used to access the results. A object. - can be used to advance the reader to the next result set. - + ]]> An error occurred while executing the batch. @@ -357,22 +357,23 @@ The precise semantics of batch execution vary across ADO.NET providers, especial One of the enumeration values that specifies options for batch execution and data retrieval. A token to cancel the asynchronous operation. - Providers should implement this method to provide a non-default implementation for overloads. - - The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by ExecuteReader will be communicated via the returned Task Exception property. - + Providers should implement this method to provide a non-default implementation for overloads. + + The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by ExecuteReader will be communicated via the returned Task Exception property. + This method accepts a cancellation token that can be used to request the operation to be cancelled early. Implementations may ignore this request. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -396,15 +397,15 @@ The precise semantics of batch execution vary across ADO.NET providers, especial Executes the batch against its connection object, returning the total number of rows affected across all the batch commands. The total number of rows affected across all the batch commands. - to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database by executing UPDATE, INSERT, or DELETE statements. - - Although does not return any rows, any output parameters or return values mapped to parameters are populated with data. - - For UPDATE, INSERT, and DELETE statements, the return value is the total number of rows affected by the batch. If no UPDATE, INSERT, or DELETE statements are included in the batch, the return value is -1. - + to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database by executing UPDATE, INSERT, or DELETE statements. + + Although does not return any rows, any output parameters or return values mapped to parameters are populated with data. + + For UPDATE, INSERT, and DELETE statements, the return value is the total number of rows affected by the batch. If no UPDATE, INSERT, or DELETE statements are included in the batch, the return value is -1. + ]]> @@ -429,24 +430,25 @@ The precise semantics of batch execution vary across ADO.NET providers, especial A token to cancel the asynchronous operation. - This is the asynchronous version of . Providers should override with an appropriate implementation. The cancellation token may optionally be ignored. - - The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by will be communicated via the returned Task Exception property. - + This is the asynchronous version of . Providers should override with an appropriate implementation. The cancellation token may optionally be ignored. + + The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by will be communicated via the returned Task Exception property. + Do not invoke other methods and properties of the object until the returned Task is complete. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> An error occurred while executing the batch. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -472,11 +474,11 @@ The precise semantics of batch execution vary across ADO.NET providers, especial Executes the batch against its connection, returning a which can be used to access the results. A object. - can be used to advance the reader to the next result set. - + ]]> @@ -504,15 +506,16 @@ The precise semantics of batch execution vary across ADO.NET providers, especial An asynchronous version of , which executes the batch against its connection, returning a which can be used to access the results. A task representing the asynchronous operation. - in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + ]]> An error occurred while executing the batch. The value is invalid. + The cancellation token was canceled. This exception is stored into the returned task. @@ -540,17 +543,18 @@ The precise semantics of batch execution vary across ADO.NET providers, especial An asynchronous version of , which executes the batch against its connection, returning a which can be used to access the results. A task representing the asynchronous operation. - in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> An error occurred while executing the batch. The value is invalid. + The cancellation token was canceled. This exception is stored into the returned task. @@ -601,6 +605,7 @@ The precise semantics of batch execution vary across ADO.NET providers, especial The first column of the first row in the first result set. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . An error occurred while executing the batch. + The cancellation token was canceled. This exception is stored into the returned task. @@ -648,6 +653,7 @@ The precise semantics of batch execution vary across ADO.NET providers, especial Asynchronously creates a prepared (or compiled) version of the batch, or of each of its commands, on the data source. A representing the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -670,13 +676,13 @@ The precise semantics of batch execution vary across ADO.NET providers, especial Gets or sets the wait time (in seconds) before terminating the attempt to execute the batch and generating an error. The time in seconds to wait for the batch to execute. - is generated if the assigned property value is less than 0. - - Note to implementers: it's recommended that 0 mean no timeout. - + is generated if the assigned property value is less than 0. + + Note to implementers: it's recommended that 0 mean no timeout. + ]]> diff --git a/xml/System.Data.Common/DbCommand.xml b/xml/System.Data.Common/DbCommand.xml index 85f8b32ab8a..8910ecab547 100644 --- a/xml/System.Data.Common/DbCommand.xml +++ b/xml/System.Data.Common/DbCommand.xml @@ -150,11 +150,11 @@ Attempts to cancel the execution of a . - ADO.NET Overview @@ -210,11 +210,11 @@ Gets or sets the text command to run against the data source. The text command to execute. The default value is an empty string (""). - to `StoredProcedure`, you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the `Execute` methods. - + to `StoredProcedure`, you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the `Execute` methods. + ]]> ADO.NET Overview @@ -260,13 +260,13 @@ Gets or sets the wait time (in seconds) before terminating the attempt to execute the command and generating an error. The time in seconds to wait for the command to execute. - is generated if the assigned property value is less than 0. - - Note to implementers, it is recommended that 0 mean no timeout. - + is generated if the assigned property value is less than 0. + + Note to implementers, it is recommended that 0 mean no timeout. + ]]> ADO.NET Overview @@ -322,11 +322,11 @@ Gets or sets how the property is interpreted. One of the enumeration values that specifies how a command string is interpreted. The default is . - to `StoredProcedure`, you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the `Execute` methods. - + to `StoredProcedure`, you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the `Execute` methods. + ]]> ADO.NET Overview @@ -741,13 +741,13 @@ Asynchronously diposes the command object. A representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -839,18 +839,18 @@ An instance of , specifying options for command execution and data retrieval. A token to cancel the asynchronous operation. - Providers should implement this method to provide a non-default implementation for overloads. - - The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by ExecuteReader will be communicated via the returned Task Exception property. - + Providers should implement this method to provide a non-default implementation for overloads. + + The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by ExecuteReader will be communicated via the returned Task Exception property. + This method accepts a cancellation token that can be used to request the operation to be cancelled early. Implementations may ignore this request. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -858,6 +858,7 @@ An error occurred while executing the command. An invalid value. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -901,15 +902,15 @@ Executes the command against its connection object, returning the number of rows affected. The number of rows affected. - to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database by executing UPDATE, INSERT, or DELETE statements. - - Although does not return any rows, any output parameters or return values mapped to parameters are populated with data. - - For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. - + to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database by executing UPDATE, INSERT, or DELETE statements. + + Although does not return any rows, any output parameters or return values mapped to parameters are populated with data. + + For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. + ]]> ADO.NET Overview @@ -923,11 +924,11 @@ This method implements the asynchronous version of , but returns a synchronously, blocking the calling thread. - An error occurred while executing the command. @@ -969,15 +970,15 @@ An asynchronous version of , which executes the command against its connection object, returning the number of rows affected. - + Invokes with CancellationToken.None. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1023,24 +1024,25 @@ A token to cancel the asynchronous operation. - This is the asynchronous version of . Providers should override with an appropriate implementation. The cancellation token may optionally be ignored. - - The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by will be communicated via the returned Task Exception property. - + This is the asynchronous version of . Providers should override with an appropriate implementation. The cancellation token may optionally be ignored. + + The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by will be communicated via the returned Task Exception property. + Do not invoke other methods and properties of the object until the returned Task is complete. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> An error occurred while executing the command. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -1147,11 +1149,11 @@ An asynchronous version of , which executes the command against its connection, returning a which can be used to access the results. - in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + ]]> ADO.NET Overview @@ -1192,15 +1194,15 @@ An asynchronous version of , which executes the command against its connection, returning a which can be used to access the results. - + Invokes with CancellationToken.None. A task representing the asynchronous operation. - in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1248,15 +1250,15 @@ One of the enumeration values that specifies how the command should execute and how data should be retrieved. An asynchronous version of , which executes the command against its connection, returning a which can be used to access the results. - + Invokes . A task representing the asynchronous operation. - in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1304,15 +1306,15 @@ A token to cancel the asynchronous operation. An asynchronous version of , which executes the command against its connection, returning a which can be used to access the results. - + Invokes . A task representing the asynchronous operation. - in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1320,6 +1322,7 @@ An error occurred while executing the command. An invalid value. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -1364,11 +1367,11 @@ Invokes . A task representing the asynchronous operation. - in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + in . For more information about asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1376,6 +1379,7 @@ An error occurred while executing the command. An invalid value. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -1420,13 +1424,13 @@ Executes the command and returns the first column of the first row in the first returned result set. All other columns, rows and result sets are ignored. The first column of the first row in the first result set. - method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the method and performing the operations necessary to generate the single value using the data returned by a . - - If the first column of the first row in the result set is not found, a null reference (`Nothing` in Visual Basic) is returned. If the value in the database is `null`, the query returns `DBNull.Value`. - + method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the method and performing the operations necessary to generate the single value using the data returned by a . + + If the first column of the first row in the result set is not found, a null reference (`Nothing` in Visual Basic) is returned. If the value in the database is `null`, the query returns `DBNull.Value`. + ]]> ADO.NET Overview @@ -1440,11 +1444,11 @@ Implements the asynchronous version of , but returns a synchronously, blocking the calling thread. - ADO.NET Overview @@ -1485,16 +1489,16 @@ - An asynchronous version of , which executes the command and returns the first column of the first row in the first returned result set. All other columns, rows and result sets are ignored. - + An asynchronous version of , which executes the command and returns the first column of the first row in the first returned result set. All other columns, rows and result sets are ignored. + Invokes with CancellationToken.None. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1541,24 +1545,25 @@ A token to cancel the asynchronous operation. - This is the asynchronous version of . Providers should override with an appropriate implementation. The cancellation token may optionally be ignored. - - The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by ExecuteScalar will be communicated via the returned Task Exception property. - + This is the asynchronous version of . Providers should override with an appropriate implementation. The cancellation token may optionally be ignored. + + The default implementation invokes the synchronous method and returns a completed task, blocking the calling thread. The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceptions thrown by ExecuteScalar will be communicated via the returned Task Exception property. + Do not invoke other methods and properties of the object until the returned Task is complete. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> An error occurred while executing the command. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -1651,11 +1656,11 @@ Creates a prepared (or compiled) version of the command on the data source. - property is set to `TableDirect`, `Prepare` does nothing. If is set to `StoredProcedure`, the call to `Prepare` should succeed, although it may result in a no-op. - + property is set to `TableDirect`, `Prepare` does nothing. If is set to `StoredProcedure`, the call to `Prepare` should succeed, although it may result in a no-op. + ]]> ADO.NET Overview @@ -1694,19 +1699,20 @@ Asynchronously creates a prepared (or compiled) version of the command on the data source. A representing the asynchronous operation. - property is set to `TableDirect`, `PrepareAsync` does nothing. If is set to `StoredProcedure`, the call to `PrepareAsync` should succeed, although it may result in a no-op. - + If the property is set to `TableDirect`, `PrepareAsync` does nothing. If is set to `StoredProcedure`, the call to `PrepareAsync` should succeed, although it may result in a no-op. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1749,11 +1755,11 @@ Gets or sets the used by this instance of the . The connection to the data source. - . - + . + ]]> ADO.NET Overview @@ -1799,13 +1805,13 @@ Creates a new instance of an object. An object. - instance is cast to an interface. - - For more information, see . - + instance is cast to an interface. + + For more information, see . + ]]> ADO.NET Overview @@ -1862,13 +1868,13 @@ Executes the against the and builds an . An object. - instance is cast to an interface. - - For more information, see . - + instance is cast to an interface. + + For more information, see . + ]]> ADO.NET Overview @@ -1917,13 +1923,13 @@ Executes the against the , and builds an using one of the values. An object. - instance is cast to an interface. - - For more information, see . - + instance is cast to an interface. + + For more information, see . + ]]> ADO.NET Overview @@ -1968,13 +1974,13 @@ Gets the . The parameters of the SQL statement or stored procedure. - instance is cast to an interface. - - For more information, see . - + instance is cast to an interface. + + For more information, see . + ]]> ADO.NET Overview @@ -2020,11 +2026,11 @@ Gets or sets the within which this object executes. The transaction within which a object of a .NET Framework data provider executes. The default value is a null reference ( in Visual Basic). - . - + . + ]]> ADO.NET Overview @@ -2131,11 +2137,11 @@ Gets or sets how command results are applied to the when used by the Update method of a . One of the enumeration values that indicates how command results are applied. The default is unless the command is automatically generated. Then the default is . - if the value entered was not one of the values. - + if the value entered was not one of the values. + ]]> ADO.NET Overview diff --git a/xml/System.Data.Common/DbConnection.xml b/xml/System.Data.Common/DbConnection.xml index d355d0000e4..4fd88afd6a1 100644 --- a/xml/System.Data.Common/DbConnection.xml +++ b/xml/System.Data.Common/DbConnection.xml @@ -156,11 +156,11 @@ When overridden in a derived class, starts a database transaction. An object representing the new transaction. - ADO.NET Overview @@ -202,17 +202,18 @@ Asynchronously starts a database transaction. A task whose property is an object representing the new transaction. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -223,11 +224,11 @@ Starts a database transaction. - Transactions and Concurrency (ADO.NET) @@ -272,11 +273,11 @@ Starts a database transaction. An object representing the new transaction. - Transactions and Concurrency (ADO.NET) @@ -361,19 +362,20 @@ Asynchronously begins a database transaction. A task whose property is an object representing the new transaction. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -411,17 +413,18 @@ Asynchronously begins a database transaction. A task whose property is an object representing the new transaction. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -449,9 +452,9 @@ if this instance supports the class; otherwise, . The default is . - should override this to return `true`. @@ -502,11 +505,11 @@ This property returns `false` by default; providers that implement The name of the database for the connection to use. When overridden in a derived class, changes the current database for an open connection. - ADO.NET Overview @@ -547,19 +550,20 @@ This property returns `false` by default; providers that implement Asynchronously changes the current database for an open connection. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -602,18 +606,18 @@ This property returns `false` by default; providers that implement When overridden in a derived class, closes the connection to the database. - and methods roll back any pending transactions. They then release the connection to the connection pool, or close the connection if connection pooling is disabled. - - An application can call or more than one time. No exception is generated. - - If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`, which are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, this also releases the physical connection. - + and methods roll back any pending transactions. They then release the connection to the connection pool, or close the connection if connection pooling is disabled. + + An application can call or more than one time. No exception is generated. + + If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`, which are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, this also releases the physical connection. + > [!CAUTION] -> Do not close or dispose a `DbConnection`, a `DbDataReader`, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/). - +> Do not close or dispose a `DbConnection`, a `DbDataReader`, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/). + ]]> @@ -652,22 +656,22 @@ This property returns `false` by default; providers that implement Asynchronously closes the connection to the database. A representing the asynchronous operation. - and methods roll back any pending transactions. They then release the connection to the connection pool, or close the connection if connection pooling is disabled. - - An application can call or more than one time. No exception is generated. - - If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`, which are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, this also releases the physical connection. - + + The and methods roll back any pending transactions. They then release the connection to the connection pool, or close the connection if connection pooling is disabled. + + An application can call or more than one time. No exception is generated. + + If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`, which are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, this also releases the physical connection. + > [!CAUTION] -> Do not close or dispose a `DbConnection`, a `DbDataReader`, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/). - +> Do not close or dispose a `DbConnection`, a `DbDataReader`, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -732,11 +736,11 @@ This property returns `false` by default; providers that implement When overridden in a derived class, gets or sets the string used to open the connection. The connection string used to establish the initial connection. The exact contents of the connection string depend on the specific data source for this connection. The default value is an empty string. - Connection Strings (ADO.NET) @@ -918,11 +922,11 @@ This property returns `false` by default; providers that implement When overridden in a derived class, creates and returns a object associated with the current connection. A object. - object. - + object. + ]]> Commands (ADO.NET) @@ -969,11 +973,11 @@ This property returns `false` by default; providers that implement When overridden in a derived class, gets the name of the current database after a connection is opened, or the database name specified in the connection string before the connection is opened. The name of the current database or the name of the database to be used after a connection is opened. The default value is an empty string. - ADO.NET Overview @@ -1016,11 +1020,11 @@ This property returns `false` by default; providers that implement When overridden in a derived class, gets the name of the database server to which to connect. The name of the database server to which to connect. The default value is an empty string. - returns whatever is contained in the for the `DataSource` keyword. If the connection is open and the data source keyword's value starts with "|`datadirectory`|", the property returns whatever is contained in the for the `DataSource` keyword only. If the connection to the database is open, the property returns what the native provider returns for the `DBPROP_INIT_DATASOURCE`, and if that is empty, the native provider's `DBPROP_DATASOURCENAME` is returned. - + returns whatever is contained in the for the `DataSource` keyword. If the connection is open and the data source keyword's value starts with "|`datadirectory`|", the property returns whatever is contained in the for the `DataSource` keyword only. If the connection to the database is open, the property returns what the native provider returns for the `DBPROP_INIT_DATASOURCE`, and if that is empty, the native provider's `DBPROP_DATASOURCENAME` is returned. + ]]> Connection Strings (ADO.NET) @@ -1157,13 +1161,13 @@ This property returns `false` by default; providers that implement Asynchronously diposes the connection object. A representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1209,11 +1213,11 @@ This property returns `false` by default; providers that implement A reference to an existing in which to enlist. Enlists in the specified transaction. - instance, `EnlistTransaction` takes advantage of functionality available in the namespace for managing distributed transactions. Once a connection is explicitly enlisted in a transaction, it cannot be unenlisted or enlisted in another transaction until the first transaction finishes. - + instance, `EnlistTransaction` takes advantage of functionality available in the namespace for managing distributed transactions. Once a connection is explicitly enlisted in a transaction, it cannot be unenlisted or enlisted in another transaction until the first transaction finishes. + ]]> Transactions and Concurrency (ADO.NET) @@ -1229,11 +1233,11 @@ This property returns `false` by default; providers that implement Returns schema information for the data source of this . - Obtaining Schema Information from a Database @@ -1276,11 +1280,11 @@ This property returns `false` by default; providers that implement Returns schema information for the data source of this . A that contains schema information. - Obtaining Schema Information from a Database @@ -1326,11 +1330,11 @@ This property returns `false` by default; providers that implement Returns schema information for the data source of this using the specified string for the schema name. A that contains schema information. - @@ -1381,15 +1385,15 @@ This property returns `false` by default; providers that implement Returns schema information for the data source of this using the specified string for the schema name and the specified string array for the restriction values. A that contains schema information. - @@ -1430,6 +1434,7 @@ This property returns `false` by default; providers that implement will be communicated via the returned Task Exception property. A task representing the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1466,6 +1471,7 @@ This property returns `false` by default; providers that implement will be communicated via the returned Task Exception property. A task representing the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1504,6 +1510,7 @@ This property returns `false` by default; providers that implement will be communicated via the returned Task Exception property. A task representing the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1546,11 +1553,11 @@ This property returns `false` by default; providers that implement A that contains the event data. Raises the event. - @@ -1599,11 +1606,11 @@ This property returns `false` by default; providers that implement When overridden in a derived class, opens a database connection with the settings specified by the . - will throw an exception if called again without first being closed. - + will throw an exception if called again without first being closed. + ]]> ADO.NET Overview @@ -1618,11 +1625,11 @@ This property returns `false` by default; providers that implement An error occurred while opening the connection. This method implements an asynchronous version of . - ADO.NET Overview @@ -1665,15 +1672,15 @@ This property returns `false` by default; providers that implement An asynchronous version of , which opens a database connection with the settings specified by the . This method invokes the virtual method with CancellationToken.None. A task representing the asynchronous operation. - , must return until the returned is completed. Then, if the connection was successful, must return . If the connection fails, must return . - - A call to will attempt to cancel or close the corresponding call. - - For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + , must return until the returned is completed. Then, if the connection was successful, must return . If the connection fails, must return . + + A call to will attempt to cancel or close the corresponding call. + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1718,27 +1725,28 @@ This property returns `false` by default; providers that implement The cancellation instruction. - This is the asynchronous version of . Providers should override with an appropriate implementation. The cancellation token can optionally be honored. - - The default implementation invokes the synchronous call and returns a completed task. The default implementation will return a cancelled task if passed an already cancelled cancellationToken. Exceptions thrown by Open will be communicated via the returned Task Exception property. - + This is the asynchronous version of . Providers should override with an appropriate implementation. The cancellation token can optionally be honored. + + The default implementation invokes the synchronous call and returns a completed task. The default implementation will return a cancelled task if passed an already cancelled cancellationToken. Exceptions thrown by Open will be communicated via the returned Task Exception property. + Do not invoke other methods and properties of the object until the returned Task is complete. A task representing the asynchronous operation. - , must return until the returned is completed. Then, if the connection was successful, must return . If the connection fails, must return . - - A call to will attempt to cancel or close the corresponding call. - - For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + , must return until the returned is completed. Then, if the connection was successful, must return . If the connection fails, must return . + + A call to will attempt to cancel or close the corresponding call. + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -1875,11 +1883,11 @@ This property returns `false` by default; providers that implement Occurs when the state of the connection changes. - event occurs when the state of the connection changes from closed to opened or from opened to closed. - + event occurs when the state of the connection changes from closed to opened or from opened to closed. + ]]> ADO.NET Overview @@ -1936,13 +1944,13 @@ This property returns `false` by default; providers that implement Begins a database transaction. An object that represents the new transaction. - instance is cast to an interface. - - For more information, see . - + instance is cast to an interface. + + For more information, see . + ]]> ADO.NET Overview @@ -1991,11 +1999,11 @@ This property returns `false` by default; providers that implement Begins a database transaction with the specified isolation level. An object that represents the new transaction. - . - + . + ]]> ADO.NET Overview @@ -2041,11 +2049,11 @@ This property returns `false` by default; providers that implement Creates and returns a object that is associated with the current connection. A object that is associated with the connection. - . - + . + ]]> ADO.NET Overview diff --git a/xml/System.Data.Common/DbDataReader.xml b/xml/System.Data.Common/DbDataReader.xml index 59de4c9530b..d2c0820e21d 100644 --- a/xml/System.Data.Common/DbDataReader.xml +++ b/xml/System.Data.Common/DbDataReader.xml @@ -196,13 +196,13 @@ Asynchronously closes the object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -249,11 +249,11 @@ Gets a value indicating the depth of nesting for the current row. The depth of nesting for the current row. - ADO.NET Overview @@ -316,16 +316,16 @@ Releases all resources used by the current instance of the class. - . Calling one of these methods leaves the in an unusable state. After disposing, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. - - For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + . Calling one of these methods leaves the in an unusable state. After disposing, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + + For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + > [!NOTE] -> Always dispose before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's `Finalize` method. - +> Always dispose before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's `Finalize` method. + ]]> ADO.NET Overview @@ -372,11 +372,11 @@ to release managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - . - + . + ]]> ADO.NET Overview @@ -416,18 +416,18 @@ Asynchronously releases all resources used by the current instance of the class. A representing the asynchronous operation. - . Calling one of these methods leaves the in an unusable state. After disposing, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. - - For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + . Calling one of these methods leaves the in an unusable state. After disposing, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + + For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + > [!NOTE] -> Always dispose before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's `Finalize` method. - +> Always dispose before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's `Finalize` method. + The default implementation of this asynchronous method delegates to its synchronous counterpart and returns a completed `ValueTask`, potentially blocking the calling thread. - + Data providers that support [asynchronous programming](/dotnet/framework/data/adonet/asynchronous-programming) should override the default implementation using asynchronous I/O operations. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . @@ -476,11 +476,11 @@ When overridden in a derived class, gets the number of columns in the current row. The number of columns in the current row. - to exclude hidden fields. - + to exclude hidden fields. + ]]> There is no current connection to an instance of SQL Server. @@ -780,6 +780,7 @@ Exceptions thrown by will be communicated via the returned Task Exception property. A task representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -877,20 +878,20 @@ When overridden in a derived class, gets name of the data type of the specified column. The name of the data type. - The column index is out of range. @@ -1145,13 +1146,13 @@ private static void GetDataTypes(String connectionString) When overridden in a derived class, returns an enumerator that can be used to iterate through the rows in the data reader. An enumerator that can be used to iterate through the rows in the data reader. - or ensure that your enumerator returns objects. - + or ensure that your enumerator returns objects. + ]]> ADO.NET Overview @@ -1250,19 +1251,19 @@ private static void GetDataTypes(String connectionString) Gets the value of the specified column as the requested type. The value of the specified column. To be added. - The connection was dropped or closed during data retrieval. + The connection was dropped or closed during data retrieval. -or- - - The data reader was closed during data retrieval. - + + The data reader was closed during data retrieval. + -or- - There is no data ready to be read (for example, the first hasn't been called, or it returned ). + There is no data ready to be read (for example, the first hasn't been called, or it returned ). -or- - The reader tried to read a previously-read column in sequential mode. + The reader tried to read a previously-read column in sequential mode. -or- @@ -1325,9 +1326,9 @@ private static void GetDataTypes(String connectionString) A task whose contains the value of the specified column. - The connection was dropped or closed during data retrieval. - + The connection was dropped or closed during data retrieval. + -or- - The data reader was closed during the data retrieval. + The data reader was closed during the data retrieval. -or- @@ -1350,7 +1351,7 @@ private static void GetDataTypes(String connectionString) -or- - Tried to read a previously-read column in sequential mode. + Tried to read a previously-read column in sequential mode. -or- @@ -1406,9 +1407,9 @@ private static void GetDataTypes(String connectionString) A task whose contains the value of the specified column. - The connection was dropped or closed during data retrieval. - + The connection was dropped or closed during data retrieval. + -or- - The data reader was closed during the data retrieval. + The data reader was closed during the data retrieval. -or- @@ -1432,13 +1433,14 @@ private static void GetDataTypes(String connectionString) -or- - Tried to read a previously-read column in sequential mode. + Tried to read a previously-read column in sequential mode. -or- There was an asynchronous operation in progress. This applies to all Get_*_ methods when running in sequential mode, as they could be called while reading a stream. The column index is out of range. The value returned by the database doesn't match or cannot be cast to . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1632,33 +1634,33 @@ private static void GetDataTypes(String connectionString) When overridden in a derived class, gets the value of the specified column as a 32-bit signed integer. The value of the specified column. - The column index is out of range. @@ -1908,11 +1910,11 @@ private static void GetCredits(String connectionString) Gets the value of the specified column as an instance of a provider-specific type. The value of the specified column. - . - + . + ]]> ADO.NET Overview @@ -2051,6 +2053,7 @@ Returns if the executed command returned no resultset, o Exceptions thrown by will be communicated via the returned Task Exception property. A task representing the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2093,25 +2096,25 @@ Returns if the executed command returned no resultset, o Gets a stream to retrieve data from the specified column. A stream. - only supports the retrieval of values that can be converted to byte arrays. + only supports the retrieval of values that can be converted to byte arrays. ]]> - The connection was dropped or closed during the data retrieval. - + The connection was dropped or closed during the data retrieval. + -or- - The data reader is closed during the data retrieval. + The data reader is closed during the data retrieval. -or- - There is no data ready to be read (for example, the first hasn't been called, or returned false). + There is no data ready to be read (for example, the first hasn't been called, or returned false). -or- - The data reader tried to read a previously-read column in sequential mode. + The data reader tried to read a previously-read column in sequential mode. -or- @@ -2209,25 +2212,25 @@ Returns if the executed command returned no resultset, o Gets a text reader to retrieve data from the column. A text reader. - only supports the retrieval of values that can be converted to character arrays (strings). + only supports the retrieval of values that can be converted to character arrays (strings). ]]> - The connection was dropped or closed during the data retrieval. - + The connection was dropped or closed during the data retrieval. + -or- - The data reader is closed during the data retrieval. + The data reader is closed during the data retrieval. -or- - There is no data ready to be read (for example, the first hasn't been called, or returned false). + There is no data ready to be read (for example, the first hasn't been called, or returned false). -or- - The data reader tried to read a previously-read column in sequential mode. + The data reader tried to read a previously-read column in sequential mode. -or- @@ -2465,11 +2468,11 @@ Returns if the executed command returned no resultset, o if the specified column is equivalent to ; otherwise, . - , , and so on) to avoid throwing an exception. - + , , and so on) to avoid throwing an exception. + ]]> The column index is out of range. @@ -2529,7 +2532,7 @@ Returns if the executed command returned no resultset, o if the executed command returned no resultset, o ]]> - The connection was dropped or closed during the data retrieval. - + The connection was dropped or closed during the data retrieval. + -or- - The data reader is closed during the data retrieval. + The data reader is closed during the data retrieval. -or- - There is no data ready to be read (for example, the first hasn't been called, or returned false). + There is no data ready to be read (for example, the first hasn't been called, or returned false). -or- - Trying to read a previously read column in sequential mode. + Trying to read a previously read column in sequential mode. -or- @@ -2607,7 +2610,7 @@ Returns if the executed command returned no resultset, o if the executed command returned no resultset, o Data providers that support [asynchronous programming](/dotnet/framework/data/adonet/asynchronous-programming) should override the default implementation using asynchronous I/O operations. This method accepts a cancellation token that can be used to request the operation to be cancelled early. Implementations may ignore this request. - + Other methods and properties of the DbDataReader object should not be invoked while the returned Task is not yet completed. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - The connection was dropped or closed during the data retrieval. - + The connection was dropped or closed during the data retrieval. + -or- - The data reader is closed during the data retrieval. + The data reader is closed during the data retrieval. -or- - There is no data ready to be read (for example, the first hasn't been called, or returned false). + There is no data ready to be read (for example, the first hasn't been called, or returned false). -or- - Trying to read a previously read column in sequential mode. + Trying to read a previously read column in sequential mode. -or- - + There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. The column index is out of range. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2790,11 +2794,11 @@ Returns if the executed command returned no resultset, o if there are more result sets; otherwise, . - ADO.NET Overview @@ -2808,11 +2812,11 @@ Returns if the executed command returned no resultset, o Asynchronously advances the reader to the next result when reading the results of a batch of statements. - ADO.NET Overview @@ -2855,8 +2859,8 @@ Returns if the executed command returned no resultset, o Asynchronously advances the reader to the next result when reading the results of a batch of statements. A task whose property is if there are more result sets or if there aren't. - if the executed command returned no resultset, o Asynchronously advances the reader to the next result when reading the results of a batch of statements. A whose property is if there are more result sets or if there aren't. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . @@ -2925,6 +2929,7 @@ Returns if the executed command returned no resultset, o An error occurred while executing the command text. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -2969,11 +2974,11 @@ Returns if the executed command returned no resultset, o if there are more rows; otherwise, . - to begin accessing data. - + to begin accessing data. + ]]> ADO.NET Overview @@ -2987,11 +2992,11 @@ Returns if the executed command returned no resultset, o Asynchronously advances the reader to the next record in a result set. - ADO.NET Overview @@ -3034,12 +3039,12 @@ Returns if the executed command returned no resultset, o Asynchronously advances the reader to the next record in a result set. A whose property is if there are more rows or if there aren't. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . @@ -3090,14 +3095,14 @@ Returns if the executed command returned no resultset, o Asynchronously advances the reader to the next record in a result set. A whose property is if there are more rows or if there aren't. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . @@ -3106,6 +3111,7 @@ Returns if the executed command returned no resultset, o An error occurred while executing the command text. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -3148,11 +3154,11 @@ Returns if the executed command returned no resultset, o When overridden in a derived class, gets the number of rows changed, inserted, or deleted by execution of the SQL statement. The number of rows changed, inserted, or deleted. -1 for SELECT statements; 0 if no rows were affected or the statement failed. - @@ -3281,11 +3287,11 @@ This member is an explicit interface member implementation. It can be used only For a description of this member, see . An instance of to be used when the field points to more remote structured data. - instance is cast to an interface. - + instance is cast to an interface. + ]]> ADO.NET Overview @@ -3328,11 +3334,11 @@ This member is an explicit interface member implementation. It can be used only Gets the number of fields in the that are not hidden. The number of fields that are not hidden. - are visible. For example, a SELECT on a partial primary key returns the remaining parts of the key as hidden fields. The hidden fields are always appended behind the visible fields. - + are visible. For example, a SELECT on a partial primary key returns the remaining parts of the key as hidden fields. The hidden fields are always appended behind the visible fields. + ]]> ADO.NET Overview diff --git a/xml/System.Data.Common/DbDataSource.xml b/xml/System.Data.Common/DbDataSource.xml index 4eddb94799c..78102cba69c 100644 --- a/xml/System.Data.Common/DbDataSource.xml +++ b/xml/System.Data.Common/DbDataSource.xml @@ -83,9 +83,9 @@ Returns a that's ready for execution against the . A that's ready for execution against the . - ; their does not need to be set, and doing so will throw an exception. Since these batches have no explicitly-managed connection, it is not possible to use them with transactions, and trying to set will throw an exception. To use a transaction, get a connection from and create a command against it. @@ -116,9 +116,9 @@ Returns a that's ready for execution against the . A that's ready for execution against the . - ; their does not need to be set, and doing so will throw an exception. Since these commands have no explicitly-managed connection, it is not possible to use them with transactions, and trying to set will throw an exception. To use a transaction, get a connection from and create a command against it. @@ -147,10 +147,10 @@ Returns a new, closed connection to the database represented by this . A new, closed connection to the database represented by this . - Returns a that's ready for execution against the . A that's ready for execution against the . - @@ -209,9 +209,9 @@ Returns a that's ready for execution against the . A that's ready for execution against the . - @@ -238,9 +238,9 @@ Returns a new, closed connection to the database represented by this . A new, closed connection to the database represented by this . - @@ -269,9 +269,9 @@ Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously. - represents a connection pool, disposing it should close all idle connections, and arrange for busy connections to be closed as soon as possible. ]]> @@ -301,9 +301,9 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Called by the Dispose() and Finalize() methods to release the managed and unmanaged resources used by the current instance of the class. - @@ -333,9 +333,9 @@ Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously. A task that represents the asynchronous dispose operation. - represents a connection pool, disposing it should close all idle connections, and arrange for busy connections to be closed as soon as possible. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . @@ -364,9 +364,9 @@ Performs application-defined tasks associated with freeing, releasing, or resetting managed resources asynchronously. A task that represents the asynchronous dispose operation. - @@ -393,13 +393,13 @@ Returns a new, open connection to the database represented by this . A new, open connection to the database represented by this . - @@ -426,17 +426,18 @@ Asynchronously returns a new, open connection to the database represented by this . A new, open connection to the database represented by this . - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -459,9 +460,9 @@ Returns a new, open connection to the database represented by this . A new, open connection to the database represented by this . - @@ -490,15 +491,16 @@ Asynchronously returns a new, open connection to the database represented by this . A new, open connection to the database represented by this . - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Data.Common/DbTransaction.xml b/xml/System.Data.Common/DbTransaction.xml index 29897ef8c22..b5775eda04a 100644 --- a/xml/System.Data.Common/DbTransaction.xml +++ b/xml/System.Data.Common/DbTransaction.xml @@ -188,17 +188,18 @@ Asynchronously commits the database transaction. A representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -239,11 +240,11 @@ Specifies the object associated with the transaction. The object associated with the transaction. - Transactions and Concurrency (ADO.NET) @@ -288,11 +289,11 @@ When overridden in a derived class, gets the object associated with the transaction. The object associated with the transaction. - Transactions and Concurrency (ADO.NET) @@ -307,11 +308,11 @@ Releases the unmanaged resources used by the and optionally releases the managed resources. - should rollback the transaction. However, the behavior of is provider specific, and should not replace calling . - + should rollback the transaction. However, the behavior of is provider specific, and should not replace calling . + ]]> Transactions and Concurrency (ADO.NET) @@ -358,11 +359,11 @@ Releases the unmanaged resources used by the . - should rollback the transaction. However, the behavior of is provider specific, and should not replace calling . - + should rollback the transaction. However, the behavior of is provider specific, and should not replace calling . + ]]> Transactions and Concurrency (ADO.NET) @@ -409,11 +410,11 @@ If , this method releases all resources held by any managed objects that this references. Releases the unmanaged resources used by the and optionally releases the managed resources. - should rollback the transaction. However, the behavior of is provider specific, and should not replace calling . - + should rollback the transaction. However, the behavior of is provider specific, and should not replace calling . + ]]> Transactions and Concurrency (ADO.NET) @@ -454,13 +455,13 @@ Asynchronously diposes the transaction object. A representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -569,6 +570,7 @@ Destroys a savepoint previously defined in the current transaction. This allows the system to reclaim some resources before the transaction ends. A representing the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -677,17 +679,18 @@ Asynchronously rolls back a transaction from a pending state. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -719,6 +722,7 @@ Rolls back all commands that were executed after the specified savepoint was established. A representing the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -779,6 +783,7 @@ Creates a savepoint in the transaction. This allows all commands that are executed after the savepoint was established to be rolled back, restoring the transaction state to what it was at the time of the savepoint. A representing the asynchronous operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Data.SqlClient/SqlBulkCopy.xml b/xml/System.Data.SqlClient/SqlBulkCopy.xml index 6d86488ad43..1c80cc29e94 100644 --- a/xml/System.Data.SqlClient/SqlBulkCopy.xml +++ b/xml/System.Data.SqlClient/SqlBulkCopy.xml @@ -36,26 +36,26 @@ Lets you efficiently bulk load a SQL Server table with data from another source. - class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but offers a significant performance advantage over them. - - The class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a instance or read with a instance. - - will fail when bulk loading a column of type into a SQL Server column whose type is one of the date/time types added in SQL Server 2008. - - - -## Examples - The following console application demonstrates how to load data using the class. In this example, a is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database. - + class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but offers a significant performance advantage over them. + + The class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a instance or read with a instance. + + will fail when bulk loading a column of type into a SQL Server column whose type is one of the date/time types added in SQL Server 2008. + + + +## Examples + The following console application demonstrates how to load data using the class. In this example, a is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -107,24 +107,24 @@ The already open instance that will be used to perform the bulk copy operation. If your connection string does not use , you can use to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. Initializes a new instance of the class using the specified open instance of . - instance is initialized, the connection remains open after the instance is closed. - - If the `connection` argument is null, an is thrown. - - - -## Examples - The following console application demonstrates how to bulk load data using a connection that is already open. In this example, a is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database. This example is for demonstration purposes only. You would not use `SqlBulkCopy` to move data from one table to another in the same database in a production application. Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - + instance is initialized, the connection remains open after the instance is closed. + + If the `connection` argument is null, an is thrown. + + + +## Examples + The following console application demonstrates how to bulk load data using a connection that is already open. In this example, a is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database. This example is for demonstration purposes only. You would not use `SqlBulkCopy` to move data from one table to another in the same database in a production application. Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -166,26 +166,26 @@ The string defining the connection that will be opened for use by the instance. If your connection string does not use , you can use or and to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. Initializes and opens a new instance of based on the supplied . The constructor uses the to initialize a new instance of the class. - is thrown. If `connectionString` is an empty string, an is thrown. - - - -## Examples - The following console application demonstrates how to bulk load data by using a connection specified as a string. The connection is automatically closed when the instance is closed. - - In this example, the source data is first read from a SQL Server table to a instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - + is thrown. If `connectionString` is an empty string, an is thrown. + + + +## Examples + The following console application demonstrates how to bulk load data by using a connection specified as a string. The connection is automatically closed when the instance is closed. + + In this example, the source data is first read from a SQL Server table to a instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ConnectionString/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ConnectionString/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ConnectionString/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -229,22 +229,22 @@ A combination of values from the enumeration that determines which data source rows are copied to the destination table. Initializes and opens a new instance of based on the supplied . The constructor uses that to initialize a new instance of the class. The instance behaves according to options supplied in the parameter. - topic. - - - -## Examples - The following console application demonstrates how to perform a bulk load by using a connection specified as a string. An option is set to use the value in the identity column of the source table when you load the destination table. In this example, the source data is first read from a SQL Server table to a instance. The source table and destination table each include an Identity column. By default, a new value for the **Identity** column is generated in the destination table for each row added. In this example, an option is set when the connection is opened that forces the bulk load process to use the **Identity** values from the source table instead. To see how the option changes the way the bulk load works, run the sample with the **dbo.BulkCopyDemoMatchingColumns** table empty. All rows load from the source. Then run the sample again without emptying the table. An exception is thrown and the code writes a message to the console notifying you that rows weren't added because of primary key constraint violations. - + topic. + + + +## Examples + The following console application demonstrates how to perform a bulk load by using a connection specified as a string. An option is set to use the value in the identity column of the source table when you load the destination table. In this example, the source data is first read from a SQL Server table to a instance. The source table and destination table each include an Identity column. By default, a new value for the **Identity** column is generated in the destination table for each row added. In this example, an option is set when the connection is opened that forces the bulk load process to use the **Identity** values from the source table instead. To see how the option changes the way the bulk load works, run the sample with the **dbo.BulkCopyDemoMatchingColumns** table empty. All rows load from the source. Then run the sample again without emptying the table. An exception is thrown and the code writes a message to the console notifying you that rows weren't added because of primary key constraint violations. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.KeepIdentity/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.KeepIdentity/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.KeepIdentity/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -290,13 +290,13 @@ An existing instance under which the bulk copy will occur. Initializes a new instance of the class using the supplied existing open instance of . The instance behaves according to options supplied in the parameter. If a non-null is supplied, the copy operations will be performed within that transaction. - Bulk Copy Operations in SQL Server @@ -338,30 +338,30 @@ Number of rows in each batch. At the end of each batch, the rows in the batch are sent to the server. The integer value of the property, or zero if no value has been set. - rows have been processed or there are no more rows to send to the destination data source. - - Zero (the default) indicates that each operation is a single batch. - - If the instance has been declared without the option in effect, rows are sent to the server rows at a time, but no transaction-related action is taken. If is in effect, each batch of rows is inserted as a separate transaction. - - The property can be set at any time. If a bulk copy is already in progress, the current batch is sized according to the previous batch size. Subsequent batches use the new size. If the is initially zero and changed while a operation is already in progress, that operation loads the data as a single batch. Any subsequent operations on the same instance use the new . - - - -## Examples - The following console application demonstrates how to bulk load data in batches of 50 rows. For an example illustrating how works with a transaction, see [Transaction and Bulk Copy Operations](/dotnet/framework/data/adonet/sql/transaction-and-bulk-copy-operations). - - In this example, the source data is first read from a SQL Server table to a instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - + rows have been processed or there are no more rows to send to the destination data source. + + Zero (the default) indicates that each operation is a single batch. + + If the instance has been declared without the option in effect, rows are sent to the server rows at a time, but no transaction-related action is taken. If is in effect, each batch of rows is inserted as a separate transaction. + + The property can be set at any time. If a bulk copy is already in progress, the current batch is sized according to the previous batch size. Subsequent batches use the new size. If the is initially zero and changed while a operation is already in progress, that operation loads the data as a single batch. Any subsequent operations on the same instance use the new . + + + +## Examples + The following console application demonstrates how to bulk load data in batches of 50 rows. For an example illustrating how works with a transaction, see [Transaction and Bulk Copy Operations](/dotnet/framework/data/adonet/sql/transaction-and-bulk-copy-operations). + + In this example, the source data is first read from a SQL Server table to a instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.BatchSize/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.BatchSize/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.BatchSize/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -403,24 +403,24 @@ Number of seconds for the operation to complete before it times out. The integer value of the property. The default is 30 seconds. A value of 0 indicates no limit; the bulk copy will wait indefinitely. - instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - + instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL`INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL`INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.Timeout/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.Timeout/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.Timeout/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -462,26 +462,26 @@ Closes the instance. - on the object, no other operation will succeed. Calls to the method will throw an . - - Calling the method from the event causes an to be thrown. - - Note that open instances are closed implicitly at the end of a `using` block. - - - -## Examples - The following example uses the same instance to add sales orders and their associated details to two destination tables. Because the **AdventureWorks** sales order tables are large, the sample reads only orders placed by a certain account number and bulk copies those orders and details to the destination tables. The method is used only after both bulk copy operations are complete. - + on the object, no other operation will succeed. Calls to the method will throw an . + + Calling the method from the event causes an to be thrown. + + Note that open instances are closed implicitly at the end of a `using` block. + + + +## Examples + The following example uses the same instance to add sales orders and their associated details to two destination tables. Because the **AdventureWorks** sales order tables are large, the sample reads only orders placed by a certain account number and bulk copies those orders and details to the destination tables. The method is used only after both bulk copy operations are complete. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.OrdersDetails/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.OrdersDetails/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.OrdersDetails/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -523,13 +523,13 @@ Returns a collection of items. Column mappings define the relationships between columns in the data source and columns in the destination. A collection of column mappings. By default, it is an empty collection. - collection is unnecessary. However, if the column counts differ, or the ordinal positions are not consistent, you must use to make sure that data is copied into the correct columns. - - During the execution of a bulk copy operation, this collection can be accessed, but it cannot be changed. Any attempt to change it will throw an . - + collection is unnecessary. However, if the column counts differ, or the ordinal positions are not consistent, you must use to make sure that data is copied into the correct columns. + + During the execution of a bulk copy operation, this collection can be accessed, but it cannot be changed. Any attempt to change it will throw an . + ]]> @@ -572,30 +572,30 @@ Name of the destination table on the server. The string value of the property, or null if none as been supplied. - has not been set when is called, an is thrown. - - If is modified while a operation is running, the change does not affect the current operation. The new value is used the next time a method is called. - - is a three-part name (`..`). You can qualify the table name with its database and owning schema if you choose. However, if the table name uses an underscore ("_") or any other special characters, you must escape the name using surrounding brackets as in (`[..]`). For more information, see [Database Identifiers](/sql/relational-databases/databases/database-identifiers). - - You can bulk-copy data to a temporary table by using a value such as `tempdb..#table` or `tempdb..#table` for the property. - - - -## Examples - The following console application demonstrates how to bulk load data using a connection that is already open. The destination table is a table in the **AdventureWorks** database. - - In this example, the connection is first used to read data from a SQL Server table to a instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - + has not been set when is called, an is thrown. + + If is modified while a operation is running, the change does not affect the current operation. The new value is used the next time a method is called. + + is a three-part name (`..`). You can qualify the table name with its database and owning schema if you choose. However, if the table name uses an underscore ("_") or any other special characters, you must escape the name using surrounding brackets as in (`[..]`). For more information, see [Database Identifiers](/sql/relational-databases/databases/database-identifiers). + + You can bulk-copy data to a temporary table by using a value such as `tempdb..#table` or `tempdb..#table` for the property. + + + +## Examples + The following console application demonstrates how to bulk load data using a connection that is already open. The destination table is a table in the **AdventureWorks** database. + + In this example, the connection is first used to read data from a SQL Server table to a instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.Single/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.Single/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.Single/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -637,11 +637,11 @@ if a object can stream data from an object; otherwise, false. The default is . - is `true`, reads from an object using , optimizing memory usage by using the streaming capabilities. When it's set to false, the class loads all the data returned by the object into memory before sending it to SQL Server or SQL Azure. - + is `true`, reads from an object using , optimizing memory usage by using the streaming capabilities. When it's set to false, the class loads all the data returned by the object into memory before sending it to SQL Server or SQL Azure. + ]]> @@ -681,26 +681,26 @@ Defines the number of rows to be processed before generating a notification event. The integer value of the property, or zero if the property has not been set. - property can be set at any time, even while a bulk copy operation is underway. Changes made during a bulk copy operation take effect after the next notification. The new setting applies to all subsequent operations on the same instance. - - If is set to a number less than zero, an is thrown. - - - -## Examples - The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that the event handler is called after every 50 rows copied to the table. - - In this example, the connection is first used to read data from a SQL Server table to a instance. Then a second connection is opened to bulk copy the data. Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - + property can be set at any time, even while a bulk copy operation is underway. Changes made during a bulk copy operation take effect after the next notification. The new setting applies to all subsequent operations on the same instance. + + If is set to a number less than zero, an is thrown. + + + +## Examples + The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that the event handler is called after every 50 rows copied to the table. + + In this example, the connection is first used to read data from a SQL Server table to a instance. Then a second connection is opened to bulk copy the data. Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.NotifyAfter/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.NotifyAfter/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.NotifyAfter/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -741,28 +741,28 @@ Occurs every time that the number of rows specified by the property have been processed. - and are independent. Receipt of a event does not imply that any rows have been sent to the server or committed. - - You cannot call SqlBulkCopy.Close () or SqlConnection.Close () from this event. Doing this will cause an being thrown, and the object state will not change. If the user wants to cancel the operation from the event, the property of the can be used. (See [Transaction and Bulk Copy Operations](/dotnet/framework/data/adonet/sql/transaction-and-bulk-copy-operations) for examples that use the property.) - - No action, such as transaction activity, is supported in the connection during the execution of the bulk copy operation, and it is recommended that you not use the same connection used during the event. However, you can open a different connection. - - - -## Examples - The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that the event handler is called after every 50 rows copied to the table. - - In this example, the connection is first used to read data from a SQL Server table to a instance. Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - + and are independent. Receipt of a event does not imply that any rows have been sent to the server or committed. + + You cannot call SqlBulkCopy.Close () or SqlConnection.Close () from this event. Doing this will cause an being thrown, and the object state will not change. If the user wants to cancel the operation from the event, the property of the can be used. (See [Transaction and Bulk Copy Operations](/dotnet/framework/data/adonet/sql/transaction-and-bulk-copy-operations) for examples that use the property.) + + No action, such as transaction activity, is supported in the connection during the execution of the bulk copy operation, and it is recommended that you not use the same connection used during the event. However, you can open a different connection. + + + +## Examples + The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that the event handler is called after every 50 rows copied to the table. + + In this example, the connection is first used to read data from a SQL Server table to a instance. Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.NotifyAfter/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.NotifyAfter/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.NotifyAfter/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -807,16 +807,16 @@ Releases all resources used by the current instance of the class. - . The `Dispose` method leaves the in an unusable state. After calling `Dispose`, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. - - For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + . The `Dispose` method leaves the in an unusable state. After calling `Dispose`, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + + For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + > [!NOTE] -> Always call `Dispose` before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's `Finalize` method. - +> Always call `Dispose` before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's `Finalize` method. + ]]> ADO.NET Overview @@ -830,11 +830,11 @@ Copies all rows from a data source to a destination table specified by the property of the object. - makes the connection busy. If MARS is enabled, you can interleave calls to with other commands in the same connection. - + makes the connection busy. If MARS is enabled, you can interleave calls to with other commands in the same connection. + ]]> Bulk Copy Operations in SQL Server @@ -913,26 +913,26 @@ An array of objects that will be copied to the destination table. Copies all rows from the supplied array to a destination table specified by the property of the object. - is busy serving it, and no other operations can be performed on the connection. - - The collection maps from the columns to the destination database table. - - - -## Examples - The following console application demonstrates how to bulk load data from a array. The destination table is a table in the **AdventureWorks** database. - - In this example, a is created at run time. A single row is selected from the to copy to the destination table. - + is busy serving it, and no other operations can be performed on the connection. + + The collection maps from the columns to the destination database table. + + + +## Examples + The following console application demonstrates how to bulk load data from a array. The destination table is a table in the **AdventureWorks** database. + + In this example, a is created at run time. A single row is selected from the to copy to the destination table. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.RowArray/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.RowArray/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.RowArray/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -972,28 +972,28 @@ A whose rows will be copied to the destination table. Copies all rows in the supplied to a destination table specified by the property of the object. - are copied to the destination table except those that have been deleted. - - While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. - - The collection maps from the columns to the destination database table. - - - -## Examples - The following Console application demonstrates how to bulk load data from a . The destination table is a table in the **AdventureWorks** database. - - In this example, a is created at run time and is the source of the `SqlBulkCopy` operation. - + are copied to the destination table except those that have been deleted. + + While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. + + The collection maps from the columns to the destination database table. + + + +## Examples + The following Console application demonstrates how to bulk load data from a . The destination table is a table in the **AdventureWorks** database. + + In this example, a is created at run time and is the source of the `SqlBulkCopy` operation. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DataTable/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DataTable/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DataTable/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -1033,28 +1033,28 @@ A whose rows will be copied to the destination table. Copies all rows in the supplied to a destination table specified by the property of the object. - or a similar call, so the next available row is the first row. To process multiple results, call on the data reader and call again. - - Note that using modifies the state of the reader. The method will call until it returns false, the operation is aborted, or an error occurs. This means that the data reader will be in a different state, probably at the end of the result set, when the operation is complete. - - While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. - - The collection maps from the data reader columns to the destination database table. - - - -## Examples - The following console application demonstrates how to bulk load data from a . The destination table is a table in the **AdventureWorks** database. - + or a similar call, so the next available row is the first row. To process multiple results, call on the data reader and call again. + + Note that using modifies the state of the reader. The method will call until it returns false, the operation is aborted, or an error occurs. This means that the data reader will be in a different state, probably at the end of the result set, when the operation is complete. + + While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. + + The collection maps from the data reader columns to the destination database table. + + + +## Examples + The following console application demonstrates how to bulk load data from a . The destination table is a table in the **AdventureWorks** database. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ConnectionString/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ConnectionString/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ConnectionString/VB/source.vb" id="Snippet1"::: + ]]> Bulk Copy Operations in SQL Server @@ -1096,31 +1096,31 @@ A value from the enumeration. Only rows matching the row state are copied to the destination. Copies only rows that match the supplied row state in the supplied to a destination table specified by the property of the object. - that are in the states indicated in the `rowState` argument and have not been deleted are copied to the destination table. - + that are in the states indicated in the `rowState` argument and have not been deleted are copied to the destination table. + > [!NOTE] -> If is specified, any , , and rows will also be copied to the server. No exception will be raised. - - While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. - - The collection maps from the columns to the destination database table. - - - -## Examples - The following Console application demonstrates how to bulk load only the rows in a that match a specified state. In this case, only unchanged rows are added. The destination table is a table in the **AdventureWorks** database. - - In this example, a is created at run time and three rows are added to it. Before the method is executed, one of the rows is edited. The method is called with a `DataRowState.Unchanged` `rowState` argument, so only the two unchanged rows are bulk copied to the destination. - +> If is specified, any , , and rows will also be copied to the server. No exception will be raised. + + While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. + + The collection maps from the columns to the destination database table. + + + +## Examples + The following Console application demonstrates how to bulk load only the rows in a that match a specified state. In this case, only unchanged rows are added. The destination table is a table in the **AdventureWorks** database. + + In this example, a is created at run time and three rows are added to it. Before the method is executed, one of the rows is edited. The method is called with a `DataRowState.Unchanged` `rowState` argument, so only the two unchanged rows are bulk copied to the destination. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT ... SELECT` statement to copy the data. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DataRowState/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DataRowState/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DataRowState/VB/source.vb" id="Snippet1"::: + ]]> @@ -1136,23 +1136,23 @@ An asynchronous version of , which copies all rows from a data source to a destination table specified by the property of the object. - makes the connection busy. If MARS is enabled, you can interleave calls to with other commands in the same connection. - - The number of rows that are rolled back when one fails depends on several things: - -- If is specified. - -- If you have your own transaction. - -- The value of . - - When there is an error while sending data to the server, the current batch (as specified by ) will be rolled back. If is not specified and you have your own transaction, the entire transaction will be rolled back (which includes all previous batches as well). - - Use to know how many rows were copied to the server. - + makes the connection busy. If MARS is enabled, you can interleave calls to with other commands in the same connection. + + The number of rows that are rolled back when one fails depends on several things: + +- If is specified. + +- If you have your own transaction. + +- The value of . + + When there is an error while sending data to the server, the current batch (as specified by ) will be rolled back. If is not specified and you have your own transaction, the entire transaction will be rolled back (which includes all previous batches as well). + + Use to know how many rows were copied to the server. + ]]> @@ -1239,27 +1239,27 @@ This method stores in the task it returns all non-usage exceptions that the meth The asynchronous version of , which copies all rows from the supplied array to a destination table specified by the property of the object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling multiple times for the same instance before task completion. - - Calling and for the same instance before task completion. - - The connection drops or is closed during execution. - - Returned in the task object, the object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the object is closed before method execution. - + Calling multiple times for the same instance before task completion. + + Calling and for the same instance before task completion. + + The connection drops or is closed during execution. + + Returned in the task object, the object was closed during the method execution. + + Returned in the task object, there was a connection pool timeout. + + Returned in the task object, the object is closed before method execution. + is specified in the connection string. Returned in the task object, any error returned by SQL Server that occurred while opening the connection. @@ -1296,27 +1296,27 @@ This method stores in the task it returns all non-usage exceptions that the meth The asynchronous version of , which copies all rows in the supplied to a destination table specified by the property of the object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling multiple times for the same instance before task completion. - - Calling and for the same instance before task completion. - - The connection drops or is closed during execution. - - Returned in the task object, the object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the object is closed before method execution. - + Calling multiple times for the same instance before task completion. + + Calling and for the same instance before task completion. + + The connection drops or is closed during execution. + + Returned in the task object, the object was closed during the method execution. + + Returned in the task object, there was a connection pool timeout. + + Returned in the task object, the object is closed before method execution. + is specified in the connection string. Returned in the task object, any error returned by SQL Server that occurred while opening the connection. @@ -1353,31 +1353,31 @@ This method stores in the task it returns all non-usage exceptions that the meth The asynchronous version of , which copies all rows in the supplied to a destination table specified by the property of the object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling multiple times for the same instance before task completion. - - Calling and for the same instance before task completion. - - The connection drops or is closed during execution. - - Returned in the task object, the object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the object is closed before method execution. - - The was closed before the completed returned. - - The 's associated connection was closed before the completed returned. - + Calling multiple times for the same instance before task completion. + + Calling and for the same instance before task completion. + + The connection drops or is closed during execution. + + Returned in the task object, the object was closed during the method execution. + + Returned in the task object, there was a connection pool timeout. + + Returned in the task object, the object is closed before method execution. + + The was closed before the completed returned. + + The 's associated connection was closed before the completed returned. + is specified in the connection string. Returned in the task object, any error returned by SQL Server that occurred while opening the connection. @@ -1422,6 +1422,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The asynchronous version of , which copies all rows from the supplied array to a destination table specified by the property of the object. Returns . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1455,34 +1456,35 @@ This method stores in the task it returns all non-usage exceptions that the meth An array of objects that will be copied to the destination table. The cancellation instruction. A value in this parameter makes this method equivalent to . - The asynchronous version of , which copies all rows from the supplied array to a destination table specified by the property of the object. - + The asynchronous version of , which copies all rows from the supplied array to a destination table specified by the property of the object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling multiple times for the same instance before task completion. - - Calling and for the same instance before task completion. - - The connection drops or is closed during execution. - - Returned in the task object, the object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the object is closed before method execution. - + Calling multiple times for the same instance before task completion. + + Calling and for the same instance before task completion. + + The connection drops or is closed during execution. + + Returned in the task object, the object was closed during the method execution. + + Returned in the task object, there was a connection pool timeout. + + Returned in the task object, the object is closed before method execution. + is specified in the connection string. Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1519,27 +1521,27 @@ This method stores in the task it returns all non-usage exceptions that the meth The asynchronous version of , which copies only rows that match the supplied row state in the supplied to a destination table specified by the property of the object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling multiple times for the same instance before task completion. - - Calling and for the same instance before task completion. - - The connection drops or is closed during execution. - - Returned in the task object, the object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the object is closed before method execution. - + Calling multiple times for the same instance before task completion. + + Calling and for the same instance before task completion. + + The connection drops or is closed during execution. + + Returned in the task object, the object was closed during the method execution. + + Returned in the task object, there was a connection pool timeout. + + Returned in the task object, the object is closed before method execution. + is specified in the connection string. Returned in the task object, any error returned by SQL Server that occurred while opening the connection. @@ -1575,34 +1577,35 @@ This method stores in the task it returns all non-usage exceptions that the meth A whose rows will be copied to the destination table. The cancellation instruction. A value in this parameter makes this method equivalent to . - The asynchronous version of , which copies all rows in the supplied to a destination table specified by the property of the object. - + The asynchronous version of , which copies all rows in the supplied to a destination table specified by the property of the object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling multiple times for the same instance before task completion. - - Calling and for the same instance before task completion. - - The connection drops or is closed during execution. - - Returned in the task object, the object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the object is closed before method execution. - + Calling multiple times for the same instance before task completion. + + Calling and for the same instance before task completion. + + The connection drops or is closed during execution. + + Returned in the task object, the object was closed during the method execution. + + Returned in the task object, there was a connection pool timeout. + + Returned in the task object, the object is closed before method execution. + is specified in the connection string. Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1636,38 +1639,39 @@ This method stores in the task it returns all non-usage exceptions that the meth A whose rows will be copied to the destination table. The cancellation instruction. A value in this parameter makes this method equivalent to . - The asynchronous version of , which copies all rows in the supplied to a destination table specified by the property of the object. - + The asynchronous version of , which copies all rows in the supplied to a destination table specified by the property of the object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling multiple times for the same instance before task completion. - - Calling and for the same instance before task completion. - - The connection drops or is closed during execution. - - Returned in the task object, the object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the object is closed before method execution. - - The was closed before the completed returned. - - The 's associated connection was closed before the completed returned. - + Calling multiple times for the same instance before task completion. + + Calling and for the same instance before task completion. + + The connection drops or is closed during execution. + + Returned in the task object, the object was closed during the method execution. + + Returned in the task object, there was a connection pool timeout. + + Returned in the task object, the object is closed before method execution. + + The was closed before the completed returned. + + The 's associated connection was closed before the completed returned. + is specified in the connection string. Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1703,34 +1707,35 @@ This method stores in the task it returns all non-usage exceptions that the meth A whose rows will be copied to the destination table. A value from the enumeration. Only rows matching the row state are copied to the destination. The cancellation instruction. A value in this parameter makes this method equivalent to . - The asynchronous version of , which copies only rows that match the supplied row state in the supplied to a destination table specified by the property of the object. - + The asynchronous version of , which copies only rows that match the supplied row state in the supplied to a destination table specified by the property of the object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling multiple times for the same instance before task completion. - - Calling and for the same instance before task completion. - - The connection drops or is closed during execution. - - Returned in the task object, the object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the object is closed before method execution. - + Calling multiple times for the same instance before task completion. + + Calling and for the same instance before task completion. + + The connection drops or is closed during execution. + + Returned in the task object, the object was closed during the method execution. + + Returned in the task object, there was a connection pool timeout. + + Returned in the task object, the object is closed before method execution. + is specified in the connection string. Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Data.SqlClient/SqlCommand.xml b/xml/System.Data.SqlClient/SqlCommand.xml index 1e7d94953e8..e4b7f703d71 100644 --- a/xml/System.Data.SqlClient/SqlCommand.xml +++ b/xml/System.Data.SqlClient/SqlCommand.xml @@ -97,358 +97,358 @@ Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. This class cannot be inherited. - is created, the read/write properties are set to their initial values. For a list of these values, see the constructor. - - features the following methods for executing commands at a SQL Server database: - -|Item|Description| -|----------|-----------------| -||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , generally executing commands such as INSERT, DELETE, UPDATE, and SET statements. Each call to must be paired with a call to which finishes the operation, typically on a separate thread.| -||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and retrieves one or more results sets from the server. Each call to must be paired with a call to which finishes the operation, typically on a separate thread.| -||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this . Each call to `BeginExecuteXmlReader` must be paired with a call to `EndExecuteXmlReader`, which finishes the operation, typically on a separate thread, and returns an object.| -||Executes commands that return rows. For increased performance, invokes commands using the Transact-SQL `sp_executesql` system stored procedure. Therefore, might not have the effect that you want if used to execute commands such as Transact-SQL SET statements.| -||Executes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements.| -||Retrieves a single value (for example, an aggregate value) from a database.| -||Sends the to the and builds an object.| - - You can reset the property and reuse the object. However, you must close the before you can execute a new or previous command. - - If a is generated by the method executing a , the remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the . However, the user can reopen the connection and continue. - + is created, the read/write properties are set to their initial values. For a list of these values, see the constructor. + + features the following methods for executing commands at a SQL Server database: + +|Item|Description| +|----------|-----------------| +||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , generally executing commands such as INSERT, DELETE, UPDATE, and SET statements. Each call to must be paired with a call to which finishes the operation, typically on a separate thread.| +||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and retrieves one or more results sets from the server. Each call to must be paired with a call to which finishes the operation, typically on a separate thread.| +||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this . Each call to `BeginExecuteXmlReader` must be paired with a call to `EndExecuteXmlReader`, which finishes the operation, typically on a separate thread, and returns an object.| +||Executes commands that return rows. For increased performance, invokes commands using the Transact-SQL `sp_executesql` system stored procedure. Therefore, might not have the effect that you want if used to execute commands such as Transact-SQL SET statements.| +||Executes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements.| +||Retrieves a single value (for example, an aggregate value) from a database.| +||Sends the to the and builds an object.| + + You can reset the property and reuse the object. However, you must close the before you can execute a new or previous command. + + If a is generated by the method executing a , the remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the . However, the user can reopen the connection and continue. + > [!NOTE] -> Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server. - - - -## Examples - The following example creates a , a , and a . The example reads through the data, writing it to the console. Finally, the example closes the and then the as it exits the `Using` code blocks. - +> Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server. + + + +## Examples + The following example creates a , a , and a . The example reads through the data, writing it to the console. Finally, the example closes the and then the as it exits the `Using` code blocks. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand Example/VB/source.vb" id="Snippet1"::: - - The following sample shows how to create and execute different types of SqlCommand objects. - - First you must create the sample database, by executing the following script: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand Example/VB/source.vb" id="Snippet1"::: + + The following sample shows how to create and execute different types of SqlCommand objects. + + First you must create the sample database, by executing the following script: + ```sql -USE [master] -GO - -CREATE DATABASE [MySchool] -GO - -USE [MySchool] -GO - -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -CREATE procedure [dbo].[CourseExtInfo] @CourseId int -as -select c.CourseID,c.Title,c.Credits,d.Name as DepartmentName -from Course as c left outer join Department as d on c.DepartmentID=d.DepartmentID -where c.CourseID=@CourseId - -GO - -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -create procedure [dbo].[DepartmentInfo] @DepartmentId int,@CourseCount int output -as -select @CourseCount=Count(c.CourseID) -from course as c -where c.DepartmentID=@DepartmentId - -select d.DepartmentID,d.Name,d.Budget,d.StartDate,d.Administrator -from Department as d -where d.DepartmentID=@DepartmentId - -GO - -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -Create PROCEDURE [dbo].[GetDepartmentsOfSpecifiedYear] -@Year int,@BudgetSum money output -AS -BEGIN - SELECT @BudgetSum=SUM([Budget]) - FROM [MySchool].[dbo].[Department] - Where YEAR([StartDate])=@Year - -SELECT [DepartmentID] - ,[Name] - ,[Budget] - ,[StartDate] - ,[Administrator] - FROM [MySchool].[dbo].[Department] - Where YEAR([StartDate])=@Year - -END -GO - -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -CREATE TABLE [dbo].[Course]([CourseID] [nvarchar](10) NOT NULL, -[Year] [smallint] NOT NULL, -[Title] [nvarchar](100) NOT NULL, -[Credits] [int] NOT NULL, -[DepartmentID] [int] NOT NULL, - CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED -( -[CourseID] ASC, -[Year] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] - -GO - -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -CREATE TABLE [dbo].[Department]([DepartmentID] [int] IDENTITY(1,1) NOT NULL, -[Name] [nvarchar](50) NOT NULL, -[Budget] [money] NOT NULL, -[StartDate] [datetime] NOT NULL, -[Administrator] [int] NULL, - CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED -( -[DepartmentID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] - -GO - -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -CREATE TABLE [dbo].[Person]([PersonID] [int] IDENTITY(1,1) NOT NULL, -[LastName] [nvarchar](50) NOT NULL, -[FirstName] [nvarchar](50) NOT NULL, -[HireDate] [datetime] NULL, -[EnrollmentDate] [datetime] NULL, - CONSTRAINT [PK_School.Student] PRIMARY KEY CLUSTERED -( -[PersonID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] - -GO - -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -CREATE TABLE [dbo].[StudentGrade]([EnrollmentID] [int] IDENTITY(1,1) NOT NULL, -[CourseID] [nvarchar](10) NOT NULL, -[StudentID] [int] NOT NULL, -[Grade] [decimal](3, 2) NOT NULL, - CONSTRAINT [PK_StudentGrade] PRIMARY KEY CLUSTERED -( -[EnrollmentID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] - -GO - -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -create view [dbo].[EnglishCourse] -as -select c.CourseID,c.Title,c.Credits,c.DepartmentID -from Course as c join Department as d on c.DepartmentID=d.DepartmentID -where d.Name=N'English' - -GO -INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1045', 2012, N'Calculus', 4, 7) -INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1061', 2012, N'Physics', 4, 1) -INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2021', 2012, N'Composition', 3, 2) -INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2042', 2012, N'Literature', 4, 2) -SET IDENTITY_INSERT [dbo].[Department] ON - -INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (1, N'Engineering', 350000.0000, CAST(0x0000999C00000000 AS DateTime), 2) -INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (2, N'English', 120000.0000, CAST(0x0000999C00000000 AS DateTime), 6) -INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (4, N'Economics', 200000.0000, CAST(0x0000999C00000000 AS DateTime), 4) -INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (7, N'Mathematics', 250024.0000, CAST(0x0000999C00000000 AS DateTime), 3) -SET IDENTITY_INSERT [dbo].[Department] OFF -SET IDENTITY_INSERT [dbo].[Person] ON - -INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (1, N'Hu', N'Nan', NULL, CAST(0x0000A0BF00000000 AS DateTime)) -INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (2, N'Norman', N'Laura', NULL, CAST(0x0000A0BF00000000 AS DateTime)) -INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (3, N'Olivotto', N'Nino', NULL, CAST(0x0000A0BF00000000 AS DateTime)) -INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (4, N'Anand', N'Arturo', NULL, CAST(0x0000A0BF00000000 AS DateTime)) -INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (5, N'Jai', N'Damien', NULL, CAST(0x0000A0BF00000000 AS DateTime)) -INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (6, N'Holt', N'Roger', CAST(0x000097F100000000 AS DateTime), NULL) -INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (7, N'Martin', N'Randall', CAST(0x00008B1A00000000 AS DateTime), NULL) -SET IDENTITY_INSERT [dbo].[Person] OFF -SET IDENTITY_INSERT [dbo].[StudentGrade] ON - -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (1, N'C1045', 1, CAST(3.50 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (2, N'C1045', 2, CAST(3.00 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (3, N'C1045', 3, CAST(2.50 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (4, N'C1045', 4, CAST(4.00 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (5, N'C1045', 5, CAST(3.50 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (6, N'C1061', 1, CAST(4.00 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (7, N'C1061', 3, CAST(3.50 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (8, N'C1061', 4, CAST(2.50 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (9, N'C1061', 5, CAST(1.50 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (10, N'C2021', 1, CAST(2.50 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (11, N'C2021', 2, CAST(3.50 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (12, N'C2021', 4, CAST(3.00 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (13, N'C2021', 5, CAST(3.00 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (14, N'C2042', 1, CAST(2.00 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (15, N'C2042', 2, CAST(3.50 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (16, N'C2042', 3, CAST(4.00 AS Decimal(3, 2))) -INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (17, N'C2042', 5, CAST(3.00 AS Decimal(3, 2))) -SET IDENTITY_INSERT [dbo].[StudentGrade] OFF -ALTER TABLE [dbo].[Course] WITH CHECK ADD CONSTRAINT [FK_Course_Department] FOREIGN KEY([DepartmentID]) -REFERENCES [dbo].[Department] ([DepartmentID]) -GO -ALTER TABLE [dbo].[Course] CHECK CONSTRAINT [FK_Course_Department] -GO -ALTER TABLE [dbo].[StudentGrade] WITH CHECK ADD CONSTRAINT [FK_StudentGrade_Student] FOREIGN KEY([StudentID]) -REFERENCES [dbo].[Person] ([PersonID]) -GO -ALTER TABLE [dbo].[StudentGrade] CHECK CONSTRAINT [FK_StudentGrade_Student] -GO -``` - - Next, compile and execute the following: - +USE [master] +GO + +CREATE DATABASE [MySchool] +GO + +USE [MySchool] +GO + +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE procedure [dbo].[CourseExtInfo] @CourseId int +as +select c.CourseID,c.Title,c.Credits,d.Name as DepartmentName +from Course as c left outer join Department as d on c.DepartmentID=d.DepartmentID +where c.CourseID=@CourseId + +GO + +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +create procedure [dbo].[DepartmentInfo] @DepartmentId int,@CourseCount int output +as +select @CourseCount=Count(c.CourseID) +from course as c +where c.DepartmentID=@DepartmentId + +select d.DepartmentID,d.Name,d.Budget,d.StartDate,d.Administrator +from Department as d +where d.DepartmentID=@DepartmentId + +GO + +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +Create PROCEDURE [dbo].[GetDepartmentsOfSpecifiedYear] +@Year int,@BudgetSum money output +AS +BEGIN + SELECT @BudgetSum=SUM([Budget]) + FROM [MySchool].[dbo].[Department] + Where YEAR([StartDate])=@Year + +SELECT [DepartmentID] + ,[Name] + ,[Budget] + ,[StartDate] + ,[Administrator] + FROM [MySchool].[dbo].[Department] + Where YEAR([StartDate])=@Year + +END +GO + +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE TABLE [dbo].[Course]([CourseID] [nvarchar](10) NOT NULL, +[Year] [smallint] NOT NULL, +[Title] [nvarchar](100) NOT NULL, +[Credits] [int] NOT NULL, +[DepartmentID] [int] NOT NULL, + CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED +( +[CourseID] ASC, +[Year] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] + +GO + +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE TABLE [dbo].[Department]([DepartmentID] [int] IDENTITY(1,1) NOT NULL, +[Name] [nvarchar](50) NOT NULL, +[Budget] [money] NOT NULL, +[StartDate] [datetime] NOT NULL, +[Administrator] [int] NULL, + CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED +( +[DepartmentID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] + +GO + +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE TABLE [dbo].[Person]([PersonID] [int] IDENTITY(1,1) NOT NULL, +[LastName] [nvarchar](50) NOT NULL, +[FirstName] [nvarchar](50) NOT NULL, +[HireDate] [datetime] NULL, +[EnrollmentDate] [datetime] NULL, + CONSTRAINT [PK_School.Student] PRIMARY KEY CLUSTERED +( +[PersonID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] + +GO + +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE TABLE [dbo].[StudentGrade]([EnrollmentID] [int] IDENTITY(1,1) NOT NULL, +[CourseID] [nvarchar](10) NOT NULL, +[StudentID] [int] NOT NULL, +[Grade] [decimal](3, 2) NOT NULL, + CONSTRAINT [PK_StudentGrade] PRIMARY KEY CLUSTERED +( +[EnrollmentID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] + +GO + +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +create view [dbo].[EnglishCourse] +as +select c.CourseID,c.Title,c.Credits,c.DepartmentID +from Course as c join Department as d on c.DepartmentID=d.DepartmentID +where d.Name=N'English' + +GO +INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1045', 2012, N'Calculus', 4, 7) +INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1061', 2012, N'Physics', 4, 1) +INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2021', 2012, N'Composition', 3, 2) +INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2042', 2012, N'Literature', 4, 2) +SET IDENTITY_INSERT [dbo].[Department] ON + +INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (1, N'Engineering', 350000.0000, CAST(0x0000999C00000000 AS DateTime), 2) +INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (2, N'English', 120000.0000, CAST(0x0000999C00000000 AS DateTime), 6) +INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (4, N'Economics', 200000.0000, CAST(0x0000999C00000000 AS DateTime), 4) +INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (7, N'Mathematics', 250024.0000, CAST(0x0000999C00000000 AS DateTime), 3) +SET IDENTITY_INSERT [dbo].[Department] OFF +SET IDENTITY_INSERT [dbo].[Person] ON + +INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (1, N'Hu', N'Nan', NULL, CAST(0x0000A0BF00000000 AS DateTime)) +INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (2, N'Norman', N'Laura', NULL, CAST(0x0000A0BF00000000 AS DateTime)) +INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (3, N'Olivotto', N'Nino', NULL, CAST(0x0000A0BF00000000 AS DateTime)) +INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (4, N'Anand', N'Arturo', NULL, CAST(0x0000A0BF00000000 AS DateTime)) +INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (5, N'Jai', N'Damien', NULL, CAST(0x0000A0BF00000000 AS DateTime)) +INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (6, N'Holt', N'Roger', CAST(0x000097F100000000 AS DateTime), NULL) +INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (7, N'Martin', N'Randall', CAST(0x00008B1A00000000 AS DateTime), NULL) +SET IDENTITY_INSERT [dbo].[Person] OFF +SET IDENTITY_INSERT [dbo].[StudentGrade] ON + +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (1, N'C1045', 1, CAST(3.50 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (2, N'C1045', 2, CAST(3.00 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (3, N'C1045', 3, CAST(2.50 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (4, N'C1045', 4, CAST(4.00 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (5, N'C1045', 5, CAST(3.50 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (6, N'C1061', 1, CAST(4.00 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (7, N'C1061', 3, CAST(3.50 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (8, N'C1061', 4, CAST(2.50 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (9, N'C1061', 5, CAST(1.50 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (10, N'C2021', 1, CAST(2.50 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (11, N'C2021', 2, CAST(3.50 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (12, N'C2021', 4, CAST(3.00 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (13, N'C2021', 5, CAST(3.00 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (14, N'C2042', 1, CAST(2.00 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (15, N'C2042', 2, CAST(3.50 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (16, N'C2042', 3, CAST(4.00 AS Decimal(3, 2))) +INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (17, N'C2042', 5, CAST(3.00 AS Decimal(3, 2))) +SET IDENTITY_INSERT [dbo].[StudentGrade] OFF +ALTER TABLE [dbo].[Course] WITH CHECK ADD CONSTRAINT [FK_Course_Department] FOREIGN KEY([DepartmentID]) +REFERENCES [dbo].[Department] ([DepartmentID]) +GO +ALTER TABLE [dbo].[Course] CHECK CONSTRAINT [FK_Course_Department] +GO +ALTER TABLE [dbo].[StudentGrade] WITH CHECK ADD CONSTRAINT [FK_StudentGrade_Student] FOREIGN KEY([StudentID]) +REFERENCES [dbo].[Person] ([PersonID]) +GO +ALTER TABLE [dbo].[StudentGrade] CHECK CONSTRAINT [FK_StudentGrade_Student] +GO +``` + + Next, compile and execute the following: + ```csharp -using System; -using System.Data; -using System.Data.SqlClient; -using System.Threading.Tasks; - -class Program { - - static class SqlHelper { - // Set the connection, command, and then execute the command with non query. - public static Int32 ExecuteNonQuery(String connectionString, String commandText, - CommandType commandType, params SqlParameter[] parameters) { - using (SqlConnection conn = new SqlConnection(connectionString)) { - using (SqlCommand cmd = new SqlCommand(commandText, conn)) { - // There're three command types: StoredProcedure, Text, TableDirect. The TableDirect - // type is only for OLE DB. - cmd.CommandType = commandType; - cmd.Parameters.AddRange(parameters); - - conn.Open(); - return cmd.ExecuteNonQuery(); - } - } - } - - // Set the connection, command, and then execute the command and only return one value. - public static Object ExecuteScalar(String connectionString, String commandText, - CommandType commandType, params SqlParameter[] parameters) { - using (SqlConnection conn = new SqlConnection(connectionString)) { - using (SqlCommand cmd = new SqlCommand(commandText, conn)) { - cmd.CommandType = commandType; - cmd.Parameters.AddRange(parameters); - - conn.Open(); - return cmd.ExecuteScalar(); - } - } - } - - // Set the connection, command, and then execute the command with query and return the reader. - public static SqlDataReader ExecuteReader(String connectionString, String commandText, - CommandType commandType, params SqlParameter[] parameters) { - SqlConnection conn = new SqlConnection(connectionString); - - using (SqlCommand cmd = new SqlCommand(commandText, conn)) { - cmd.CommandType = commandType; - cmd.Parameters.AddRange(parameters); - - conn.Open(); - // When using CommandBehavior.CloseConnection, the connection will be closed when the - // IDataReader is closed. - SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); - - return reader; - } - } - } - - static void Main(string[] args) { - String connectionString = "Data Source=(local);Initial Catalog=MySchool;Integrated Security=True;Asynchronous Processing=true;"; - - CountCourses(connectionString, 2012); - Console.WriteLine(); - - Console.WriteLine("Following result is the departments that started from 2007:"); - GetDepartments(connectionString, 2007); - Console.WriteLine(); - - Console.WriteLine("Add the credits when the credits of course is lower than 4."); - AddCredits(connectionString, 4); - Console.WriteLine(); - - Console.WriteLine("Please press any key to exit..."); - Console.ReadKey(); - } - - static void CountCourses(String connectionString, Int32 year) { - String commandText = "Select Count([CourseID]) FROM [MySchool].[dbo].[Course] Where Year=@Year"; - SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int); - parameterYear.Value = year; - - Object oValue = SqlHelper.ExecuteScalar(connectionString, commandText, CommandType.Text, parameterYear); - Int32 count; - if (Int32.TryParse(oValue.ToString(), out count)) - Console.WriteLine("There {0} {1} course{2} in {3}.", count > 1 ? "are" : "is", count, count > 1 ? "s" : null, year); - } - - // Display the Departments that start from the specified year. - static void GetDepartments(String connectionString, Int32 year) { - String commandText = "dbo.GetDepartmentsOfSpecifiedYear"; - - // Specify the year of StartDate - SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int); - parameterYear.Value = year; - - // When the direction of parameter is set as Output, you can get the value after - // executing the command. - SqlParameter parameterBudget = new SqlParameter("@BudgetSum", SqlDbType.Money); - parameterBudget.Direction = ParameterDirection.Output; - - using (SqlDataReader reader = SqlHelper.ExecuteReader(connectionString, commandText, - CommandType.StoredProcedure, parameterYear, parameterBudget)) { - Console.WriteLine("{0,-20}{1,-20}{2,-20}{3,-20}", "Name", "Budget", "StartDate", - "Administrator"); - while (reader.Read()) { - Console.WriteLine("{0,-20}{1,-20:C}{2,-20:d}{3,-20}", reader["Name"], - reader["Budget"], reader["StartDate"], reader["Administrator"]); - } - } - Console.WriteLine("{0,-20}{1,-20:C}", "Sum:", parameterBudget.Value); - } - - // If credits of course is lower than the certain value, the method will add the credits. - static void AddCredits(String connectionString, Int32 creditsLow) { - String commandText = "Update [MySchool].[dbo].[Course] Set Credits=Credits+1 Where Credits<@Credits"; - - SqlParameter parameterCredits = new SqlParameter("@Credits", creditsLow); - - Int32 rows = SqlHelper.ExecuteNonQuery(connectionString, commandText, CommandType.Text, parameterCredits); - - Console.WriteLine("{0} row{1} {2} updated.", rows, rows > 1 ? "s" : null, rows > 1 ? "are" : "is"); - } -} -``` - +using System; +using System.Data; +using System.Data.SqlClient; +using System.Threading.Tasks; + +class Program { + + static class SqlHelper { + // Set the connection, command, and then execute the command with non query. + public static Int32 ExecuteNonQuery(String connectionString, String commandText, + CommandType commandType, params SqlParameter[] parameters) { + using (SqlConnection conn = new SqlConnection(connectionString)) { + using (SqlCommand cmd = new SqlCommand(commandText, conn)) { + // There're three command types: StoredProcedure, Text, TableDirect. The TableDirect + // type is only for OLE DB. + cmd.CommandType = commandType; + cmd.Parameters.AddRange(parameters); + + conn.Open(); + return cmd.ExecuteNonQuery(); + } + } + } + + // Set the connection, command, and then execute the command and only return one value. + public static Object ExecuteScalar(String connectionString, String commandText, + CommandType commandType, params SqlParameter[] parameters) { + using (SqlConnection conn = new SqlConnection(connectionString)) { + using (SqlCommand cmd = new SqlCommand(commandText, conn)) { + cmd.CommandType = commandType; + cmd.Parameters.AddRange(parameters); + + conn.Open(); + return cmd.ExecuteScalar(); + } + } + } + + // Set the connection, command, and then execute the command with query and return the reader. + public static SqlDataReader ExecuteReader(String connectionString, String commandText, + CommandType commandType, params SqlParameter[] parameters) { + SqlConnection conn = new SqlConnection(connectionString); + + using (SqlCommand cmd = new SqlCommand(commandText, conn)) { + cmd.CommandType = commandType; + cmd.Parameters.AddRange(parameters); + + conn.Open(); + // When using CommandBehavior.CloseConnection, the connection will be closed when the + // IDataReader is closed. + SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); + + return reader; + } + } + } + + static void Main(string[] args) { + String connectionString = "Data Source=(local);Initial Catalog=MySchool;Integrated Security=True;Asynchronous Processing=true;"; + + CountCourses(connectionString, 2012); + Console.WriteLine(); + + Console.WriteLine("Following result is the departments that started from 2007:"); + GetDepartments(connectionString, 2007); + Console.WriteLine(); + + Console.WriteLine("Add the credits when the credits of course is lower than 4."); + AddCredits(connectionString, 4); + Console.WriteLine(); + + Console.WriteLine("Please press any key to exit..."); + Console.ReadKey(); + } + + static void CountCourses(String connectionString, Int32 year) { + String commandText = "Select Count([CourseID]) FROM [MySchool].[dbo].[Course] Where Year=@Year"; + SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int); + parameterYear.Value = year; + + Object oValue = SqlHelper.ExecuteScalar(connectionString, commandText, CommandType.Text, parameterYear); + Int32 count; + if (Int32.TryParse(oValue.ToString(), out count)) + Console.WriteLine("There {0} {1} course{2} in {3}.", count > 1 ? "are" : "is", count, count > 1 ? "s" : null, year); + } + + // Display the Departments that start from the specified year. + static void GetDepartments(String connectionString, Int32 year) { + String commandText = "dbo.GetDepartmentsOfSpecifiedYear"; + + // Specify the year of StartDate + SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int); + parameterYear.Value = year; + + // When the direction of parameter is set as Output, you can get the value after + // executing the command. + SqlParameter parameterBudget = new SqlParameter("@BudgetSum", SqlDbType.Money); + parameterBudget.Direction = ParameterDirection.Output; + + using (SqlDataReader reader = SqlHelper.ExecuteReader(connectionString, commandText, + CommandType.StoredProcedure, parameterYear, parameterBudget)) { + Console.WriteLine("{0,-20}{1,-20}{2,-20}{3,-20}", "Name", "Budget", "StartDate", + "Administrator"); + while (reader.Read()) { + Console.WriteLine("{0,-20}{1,-20:C}{2,-20:d}{3,-20}", reader["Name"], + reader["Budget"], reader["StartDate"], reader["Administrator"]); + } + } + Console.WriteLine("{0,-20}{1,-20:C}", "Sum:", parameterBudget.Value); + } + + // If credits of course is lower than the certain value, the method will add the credits. + static void AddCredits(String connectionString, Int32 creditsLow) { + String commandText = "Update [MySchool].[dbo].[Course] Set Credits=Credits+1 Where Credits<@Credits"; + + SqlParameter parameterCredits = new SqlParameter("@Credits", creditsLow); + + Int32 rows = SqlHelper.ExecuteNonQuery(connectionString, commandText, CommandType.Text, parameterCredits); + + Console.WriteLine("{0} row{1} {2} updated.", rows, rows > 1 ? "s" : null, rows > 1 ? "are" : "is"); + } +} +``` + ]]> Retrieving and Modifying Data in ADO.NET @@ -498,28 +498,28 @@ class Program { Initializes a new instance of the class. - . - -|Properties|Initial value| -|----------------|-------------------| -||empty string ("")| -||30| -||`CommandType.Text`| -||Null| - - You can change the value for any of these properties through a separate call to the property. - - - -## Examples - The following example creates a and sets the `CommandTimeout` property. - + . + +|Properties|Initial value| +|----------------|-------------------| +||empty string ("")| +||30| +||`CommandType.Text`| +||Null| + + You can change the value for any of these properties through a separate call to the property. + + + +## Examples + The following example creates a and sets the `CommandTimeout` property. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData IDbCommand.CommandTimeout Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData IDbCommand.CommandTimeout Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData IDbCommand.CommandTimeout Example/VB/source.vb" id="Snippet1"::: + ]]> Retrieving and Modifying Data in ADO.NET @@ -563,28 +563,28 @@ class Program { The text of the query. Initializes a new instance of the class with the text of the query. - is created, the following read/write properties are set to initial values. - -|Properties|Initial value| -|----------------|-------------------| -||`cmdText`| -||30| -||`CommandType.Text`| -||null| - - You can change the value for any of these properties through a separate call to the property. - - - -## Examples - The following example creates a , passing in the connection string and command text. - + is created, the following read/write properties are set to initial values. + +|Properties|Initial value| +|----------------|-------------------| +||`cmdText`| +||30| +||`CommandType.Text`| +||null| + + You can change the value for any of these properties through a separate call to the property. + + + +## Examples + The following example creates a , passing in the connection string and command text. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.SqlCommand1 Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.SqlCommand1 Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.SqlCommand1 Example/VB/source.vb" id="Snippet1"::: + ]]> Connecting and Retrieving Data in ADO.NET @@ -630,28 +630,28 @@ class Program { A that represents the connection to an instance of SQL Server. Initializes a new instance of the class with the text of the query and a . - . - -|Properties|Initial value| -|----------------|-------------------| -||`cmdText`| -||30| -||`CommandType.Text`| -||A new that is the value for the `connection` parameter.| - - You can change the value for any of these parameters by setting the related property. - - - -## Examples - The following example creates a and sets some of its properties. - + . + +|Properties|Initial value| +|----------------|-------------------| +||`cmdText`| +||30| +||`CommandType.Text`| +||A new that is the value for the `connection` parameter.| + + You can change the value for any of these parameters by setting the related property. + + + +## Examples + The following example creates a and sets some of its properties. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.SqlCommand2 Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.SqlCommand2 Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.SqlCommand2 Example/VB/source.vb" id="Snippet1"::: + ]]> Connecting and Retrieving Data in ADO.NET @@ -699,20 +699,20 @@ class Program { The in which the executes. Initializes a new instance of the class with the text of the query, a , and the . - . - -|Properties|Initial value| -|----------------|-------------------| -||`cmdText`| -||30| -||`CommandType.Text`| -||A new that is the value for the `connection` parameter.| - - You can change the value for any of these parameters by setting the related property. - + . + +|Properties|Initial value| +|----------------|-------------------| +||`cmdText`| +||30| +||`CommandType.Text`| +||A new that is the value for the `connection` parameter.| + + You can change the value for any of these parameters by setting the related property. + ]]> Connecting and Retrieving Data in ADO.NET @@ -792,42 +792,42 @@ class Program { Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this . An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns the number of affected rows. - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - - Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. - - Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . + method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. + + Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . This method ignores the property. - - - -## Examples - The following console application creates updates data within the **AdventureWorks** sample database, doing its work asynchronously. In order to emulate a long-running process, this example inserts a WAITFOR statement in the command text. Normally, you would not take efforts to make your commands run slower, but doing this in this case makes it easier to demonstrate the asynchronous behavior. - + + + +## Examples + The following console application creates updates data within the **AdventureWorks** sample database, doing its work asynchronously. In order to emulate a long-running process, this example inserts a WAITFOR statement in the command text. Normally, you would not take efforts to make your commands run slower, but doing this in this case makes it easier to demonstrate the asynchronous behavior. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteNonQuery/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteNonQuery/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteNonQuery/VB/source.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . + A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Any error that occurred while executing the command text. + Any error that occurred while executing the command text. -or- A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . + The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . -or- @@ -875,50 +875,50 @@ The closed or dropped durin Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , given a callback procedure and state information. An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns the number of affected rows. - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - - The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `asyncStateObject` parameter, and your callback procedure can retrieve this information using the property. - - Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. - - Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. - - All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. + method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `asyncStateObject` parameter, and your callback procedure can retrieve this information using the property. + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. + + Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. + + All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. This method ignores the property. - - - -## Examples - The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of several seconds (emulating a long-running command). - - This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. - - To set up this example, create a new Windows application. Put a control and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. - + + + +## Examples + The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of several seconds (emulating a long-running command). + + This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. + + To set up this example, create a new Windows application. Put a control and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteNonQueryForm/CS/Form1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteNonQueryForm/VB/Form1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteNonQueryForm/VB/Form1.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Any error that occurred while executing the command text. + Any error that occurred while executing the command text. -or- A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . + The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . -or- @@ -970,44 +970,44 @@ A other than **Xml Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , and retrieves one or more result sets from the server. An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns a instance that can be used to retrieve the returned rows. - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - - Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. - - Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . - + method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. + + Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. This method ignores the property. - - - -## Examples - The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. As soon as the process has completed, the code retrieves the and displays its contents. - + + + +## Examples + The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. As soon as the process has completed, the code retrieves the and displays its contents. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReader/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReader/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReader/VB/source.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . + A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Any error that occurred while executing the command text. + Any error that occurred while executing the command text. -or- A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . + The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . -or- @@ -1051,47 +1051,47 @@ A timeout occurred during a streaming operation. For more information about stre Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this using one of the values. An that can be used to poll, wait for results, or both; this value is also needed when invoking , which returns a instance that can be used to retrieve the returned rows. - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - - The `behavior` parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's `OR` operator); generally, developers use the `CommandBehavior.CloseConnection` value to make sure that the connection is closed by the runtime when the is closed. - - Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. - - Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . - + method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + The `behavior` parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's `OR` operator); generally, developers use the `CommandBehavior.CloseConnection` value to make sure that the connection is closed by the runtime when the is closed. + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. + + Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . + If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. This method ignores the property. - - -## Examples - The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the and displays its contents. - - This example also passes the `CommandBehavior.CloseConnection` and `CommandBehavior.SingleRow` values in the behavior parameter, causing the connection to be closed with the returned is closed, and to optimize for a single row result. - + + +## Examples + The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the and displays its contents. + + This example also passes the `CommandBehavior.CloseConnection` and `CommandBehavior.SingleRow` values in the behavior parameter, causing the connection to be closed with the returned is closed, and to optimize for a single row result. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReaderAsyncSimple/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReaderAsyncSimple/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReaderAsyncSimple/VB/source.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . + A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Any error that occurred while executing the command text. + Any error that occurred while executing the command text. -or- A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . + The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . -or- @@ -1137,52 +1137,52 @@ A timeout occurred during a streaming operation. For more information about stre Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and retrieves one or more result sets from the server, given a callback procedure and state information. An that can be used to poll, wait for results, or both; this value is also needed when invoking , which returns a instance which can be used to retrieve the returned rows. - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed cause the object to block until the execution is finished. - - The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property. - - Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. - - Because the callback procedure executes from within a background thread supplied by the Microsoft .NET runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. - - All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. - + method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed cause the object to block until the execution is finished. + + The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property. + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. + + Because the callback procedure executes from within a background thread supplied by the Microsoft .NET runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. + + All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. + If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. This method ignores the property. - - - -## Examples - The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the `stateObject` parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . - - This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. - - To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. - + + + +## Examples + The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the `stateObject` parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . + + This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. + + To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReaderAsync/CS/Form1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReaderAsync/VB/Form1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReaderAsync/VB/Form1.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Any error that occurred while executing the command text. + Any error that occurred while executing the command text. -or- A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . + The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . -or- @@ -1230,56 +1230,56 @@ A other than **Xml Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , using one of the values, and retrieving one or more result sets from the server, given a callback procedure and state information. An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns a instance which can be used to retrieve the returned rows. - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - - The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property. - - The `behavior` parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's `Or` operator); generally, developers use the `CloseConnection` value to make sure that the connection is closed by the runtime when the is closed. Developers can also optimize the behavior of the by specifying the `SingleRow` value when it is known in advance that the Transact-SQL statement or stored procedure only returns a single row. - - Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. - - Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure--should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. - - All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. - + method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property. + + The `behavior` parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's `Or` operator); generally, developers use the `CloseConnection` value to make sure that the connection is closed by the runtime when the is closed. Developers can also optimize the behavior of the by specifying the `SingleRow` value when it is known in advance that the Transact-SQL statement or stored procedure only returns a single row. + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. + + Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure--should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. + + All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. This method ignores the property. - - - -## Examples - The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the `stateObject` parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . - - This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. - - To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. - - This example passes the `CommandBehavior.CloseConnection` value in the `behavior` parameter, causing the returned to automatically close its connection when it is closed. - + + + +## Examples + The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the `stateObject` parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . + + This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. + + To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. + + This example passes the `CommandBehavior.CloseConnection` value in the `behavior` parameter, causing the returned to automatically close its connection when it is closed. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReaderAsyncBehavior/CS/Form1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReaderAsyncBehavior/VB/Form1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteReaderAsyncBehavior/VB/Form1.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . + A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Any error that occurred while executing the command text. + Any error that occurred while executing the command text. -or- A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . + The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . -or- @@ -1333,56 +1333,56 @@ A other than **Xml Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and returns results as an object. An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns a single XML value. - method starts the process of asynchronously executing a Transact-SQL statement that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the `EndExecuteXmlReader` method to finish the operation and retrieve the XML returned by the command. The method returns immediately, but until the code executes the corresponding `EndExecuteXmlReader` method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the `EndExecuteXmlReader` before the command's execution is completed causes the object to block until the execution is finished. - - The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, `CommandText` can also specify a statement that returns `ntext` data that contains valid XML. - - A typical query can be formatted as in the following C# example: - + method starts the process of asynchronously executing a Transact-SQL statement that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the `EndExecuteXmlReader` method to finish the operation and retrieve the XML returned by the command. The method returns immediately, but until the code executes the corresponding `EndExecuteXmlReader` method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the `EndExecuteXmlReader` before the command's execution is completed causes the object to block until the execution is finished. + + The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, `CommandText` can also specify a statement that returns `ntext` data that contains valid XML. + + A typical query can be formatted as in the following C# example: + ```csharp -SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM dbo.Contact FOR XML AUTO, XMLDATA", SqlConn); -``` - - This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the `EndExecuteXmlReader` method attaches the to the value on the first row, and discards the rest of the result set. - - The multiple active result set (MARS) feature lets multiple actions use the same connection. - - Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. - - Because this overload does not support a callback procedure, developers need to either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . - +SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM dbo.Contact FOR XML AUTO, XMLDATA", SqlConn); +``` + + This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the `EndExecuteXmlReader` method attaches the to the value on the first row, and discards the rest of the result set. + + The multiple active result set (MARS) feature lets multiple actions use the same connection. + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. + + Because this overload does not support a callback procedure, developers need to either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . + If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. This method ignores the property. - - - -## Examples - The following console application starts the process of retrieving XML data asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the XML and displays its contents. - + + + +## Examples + The following console application starts the process of retrieving XML data asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the XML and displays its contents. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteXmlReader/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteXmlReader/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteXmlReader/VB/source.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Any error that occurred while executing the command text. + Any error that occurred while executing the command text. -or- A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . + The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . -or- @@ -1430,62 +1430,62 @@ The closed or dropped durin Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and returns results as an object, using a callback procedure. An that can be used to poll, wait for results, or both; this value is also needed when the is called, which returns the results of the command as XML. - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the requested XML data. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - - The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, `CommandText` can also specify a statement that returns data that contains valid XML. This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. - - A typical query can be formatted as in the following C# example: - + method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the requested XML data. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, `CommandText` can also specify a statement that returns data that contains valid XML. This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. + + A typical query can be formatted as in the following C# example: + ```csharp -SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM Contact FOR XML AUTO, XMLDATA", SqlConn); -``` - - This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. - - The multiple active result set (MARS) feature lets multiple actions use the same connection. - - The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property. - - Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters is sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. - - All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. - +SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM Contact FOR XML AUTO, XMLDATA", SqlConn); +``` + + This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. + + The multiple active result set (MARS) feature lets multiple actions use the same connection. + + The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property. + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters is sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. + + All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. This method ignores the property. - - - -## Examples - The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). This example passes the executing object as the `stateObject` parameter--doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . - - This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. - - To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. - + + + +## Examples + The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). This example passes the executing object as the `stateObject` parameter--doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . + + This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. + + To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteXmlReaderAsync/CS/Form1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteXmlReaderAsync/VB/Form1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.BeginExecuteXmlReaderAsync/VB/Form1.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Any error that occurred while executing the command text. + Any error that occurred while executing the command text. -or- A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . + The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this . -or- @@ -1541,21 +1541,21 @@ The closed or dropped durin Tries to cancel the execution of a . - , then call (implicitly or explicitly) before calling , and then call , the cancel command will not be sent to SQL Server and the result set can continue to stream after you call . To avoid this, make sure that you call before closing the reader or connection. - - - -## Examples - The following example demonstrates the use of the method. - + , then call (implicitly or explicitly) before calling , and then call , the cancel command will not be sent to SQL Server and the result set can continue to stream after you call . To avoid this, make sure that you call before closing the reader or connection. + + + +## Examples + The following example demonstrates the use of the method. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.Cancel/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.Cancel/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.Cancel/VB/source.vb" id="Snippet1"::: + ]]> Connecting and Retrieving Data in ADO.NET @@ -1709,27 +1709,27 @@ The closed or dropped durin Gets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source. The Transact-SQL statement or stored procedure to execute. The default is an empty string. - property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The user may be required to use escape character syntax if the stored procedure name contains any special characters. The command executes this stored procedure when you call one of the `Execute` methods. - - The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a Transact-SQL statement or a stored procedure called by a command of `CommandType.Text`. In this case, named parameters must be used. For example: - + property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The user may be required to use escape character syntax if the stored procedure name contains any special characters. The command executes this stored procedure when you call one of the `Execute` methods. + + The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a Transact-SQL statement or a stored procedure called by a command of `CommandType.Text`. In this case, named parameters must be used. For example: + ```sql -SELECT * FROM dbo.Customers WHERE CustomerID = @CustomerID -``` - - For more information, see [Configuring Parameters and Parameter Data Types](/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types). - - - -## Examples - The following example creates a and sets some of its properties. - +SELECT * FROM dbo.Customers WHERE CustomerID = @CustomerID +``` + + For more information, see [Configuring Parameters and Parameter Data Types](/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types). + + + +## Examples + The following example creates a and sets some of its properties. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.CommandText Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.CommandText Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.CommandText Example/VB/source.vb" id="Snippet1"::: + ]]> Retrieving and Modifying Data in ADO.NET @@ -1789,48 +1789,48 @@ SELECT * FROM dbo.Customers WHERE CustomerID = @CustomerID Gets or sets the wait time (in seconds) before terminating the attempt to execute a command and generating an error. The time in seconds to wait for the command to execute. The default is 30 seconds. - [!NOTE] > The property will be ignored by older APM (Asynchronous Programming Model) asynchronous method calls such as . It will be honored by newer TAP (Task Asynchronous Programming) methods such as . - - has no effect when the command is executed against a context connection (a opened with "context connection=true" in the connection string). - + + has no effect when the command is executed against a context connection (a opened with "context connection=true" in the connection string). + > [!NOTE] -> This property is the cumulative time-out (for all network packets that are read during the invocation of a method) for all network reads during command execution or processing of the results. A time-out can still occur after the first row is returned, and does not include user processing time, only network read time. -> -> For example, with a 30 second time out, if requires two network packets, then it has 30 seconds to read both network packets. If you call again, it will have another 30 seconds to read any data that it requires. - +> This property is the cumulative time-out (for all network packets that are read during the invocation of a method) for all network reads during command execution or processing of the results. A time-out can still occur after the first row is returned, and does not include user processing time, only network read time. +> +> For example, with a 30 second time out, if requires two network packets, then it has 30 seconds to read both network packets. If you call again, it will have another 30 seconds to read any data that it requires. + ```csharp -using System; -using System.Data.SqlClient; -/// -public class A { - /// - public static void Main() { - string connectionString = ""; - // Wait for 5 second delay in the command - string queryString = "waitfor delay '00:00:05'"; - using (SqlConnection connection = new SqlConnection(connectionString)) { - connection.Open(); - SqlCommand command = new SqlCommand(queryString, connection); - // Setting command timeout to 1 second - command.CommandTimeout = 1; - try { - command.ExecuteNonQuery(); - } - catch (SqlException e) { - Console.WriteLine("Got expected SqlException due to command timeout "); - Console.WriteLine(e); - } - } - } -} -``` - +using System; +using System.Data.SqlClient; +/// +public class A { + /// + public static void Main() { + string connectionString = ""; + // Wait for 5 second delay in the command + string queryString = "waitfor delay '00:00:05'"; + using (SqlConnection connection = new SqlConnection(connectionString)) { + connection.Open(); + SqlCommand command = new SqlCommand(queryString, connection); + // Setting command timeout to 1 second + command.CommandTimeout = 1; + try { + command.ExecuteNonQuery(); + } + catch (SqlException e) { + Console.WriteLine("Got expected SqlException due to command timeout "); + Console.WriteLine(e); + } + } + } +} +``` + ]]> Connecting and Retrieving Data in ADO.NET @@ -1894,25 +1894,25 @@ public class A { Gets or sets a value indicating how the property is to be interpreted. One of the values. The default is . - property to `StoredProcedure`, you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the Execute methods. - - The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a SQL Statement or a stored procedure called with a of . In this case, named parameters must be used. For example: - - SELECT * FROM Customers WHERE CustomerID = @CustomerID - - For more information, see [Configuring Parameters and Parameter Data Types](/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types). - - - -## Examples - The following example creates a and sets some of its properties. - + property to `StoredProcedure`, you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the Execute methods. + + The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a SQL Statement or a stored procedure called with a of . In this case, named parameters must be used. For example: + + SELECT * FROM Customers WHERE CustomerID = @CustomerID + + For more information, see [Configuring Parameters and Parameter Data Types](/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types). + + + +## Examples + The following example creates a and sets some of its properties. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData IDbCommand.CommandTimeout Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData IDbCommand.CommandTimeout Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData IDbCommand.CommandTimeout Example/VB/source.vb" id="Snippet1"::: + ]]> The value was not a valid . @@ -1987,21 +1987,21 @@ public class A { Gets or sets the used by this instance of the . The connection to a data source. The default value is . - . - - If the property is not null and the transaction has already been committed or rolled back, is set to null. - - - -## Examples - The following example creates a and sets some of its properties. - + . + + If the property is not null and the transaction has already been committed or rolled back, is set to null. + + + +## Examples + The following example creates a and sets some of its properties. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.Connection Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.Connection Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.Connection Example/VB/source.vb" id="Snippet1"::: + ]]> The property was changed while the command was enlisted in a transaction. @@ -2087,11 +2087,11 @@ public class A { Creates a new instance of a object. A object. - method is a strongly-typed version of . - + method is a strongly-typed version of . + ]]> Connecting and Retrieving Data in ADO.NET @@ -2344,24 +2344,24 @@ public class A { Finishes asynchronous execution of a Transact-SQL statement. The number of rows affected (the same behavior as ). - to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. - - - -## Examples - For examples demonstrating the use of the method, see . - + to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. + + + +## Examples + For examples demonstrating the use of the method, see . + ]]> parameter is null ( in Microsoft Visual Basic) was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called to complete execution of a call to . - The amount of time specified in elapsed and the asynchronous operation specified with is not complete. - + The amount of time specified in elapsed and the asynchronous operation specified with is not complete. + -or- In some situations, can be set to incorrectly. If this occurs and is called, EndExecuteNonQuery could raise a SqlException error if the amount of time specified in elapsed and the asynchronous operation specified with is not complete. To correct this situation, you should either increase the value of CommandTimeout or reduce the work being done by the asynchronous operation. @@ -2402,16 +2402,16 @@ In some situations, can be set to Finishes asynchronous execution of a Transact-SQL statement, returning the requested . A object that can be used to retrieve the requested rows. - to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. - - - -## Examples - For examples demonstrating the use of the method, see . - + to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. + + + +## Examples + For examples demonstrating the use of the method, see . + ]]> @@ -2457,16 +2457,16 @@ In some situations, can be set to Finishes asynchronous execution of a Transact-SQL statement, returning the requested data as XML. An object that can be used to fetch the resulting XML data. - to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. - - - -## Examples - For examples demonstrating the use of the method, see . - + to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. + + + +## Examples + For examples demonstrating the use of the method, see . + ]]> @@ -2558,6 +2558,7 @@ In some situations, can be set to To be added. To be added. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2605,13 +2606,13 @@ In some situations, can be set to Executes a Transact-SQL statement against the connection and returns the number of rows affected. The number of rows affected. - to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a by executing UPDATE, INSERT, or DELETE statements. - - Although the returns no rows, any output parameters or return values mapped to parameters are populated with data. - + to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a by executing UPDATE, INSERT, or DELETE statements. + + Although the returns no rows, any output parameters or return values mapped to parameters are populated with data. + For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. @@ -2622,24 +2623,24 @@ If no statements are detected that contribute to the count, the return value is -## Examples - The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL statement (such as UPDATE, INSERT, or DELETE) and a string to use to connect to the data source. - +## Examples + The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL statement (such as UPDATE, INSERT, or DELETE) and a string to use to connect to the data source. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteNonQuery Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteNonQuery Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteNonQuery Example/VB/source.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . + A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. + An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. -or- @@ -2689,41 +2690,42 @@ If no statements are detected that contribute to the count, the return value is An asynchronous version of , which executes a Transact-SQL statement against the connection and returns the number of rows affected. The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Calling more than once for the same instance before task completion. + Calling more than once for the same instance before task completion. -or- -The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). +The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - + is specified in the connection string. - SQL Server returned an error while executing the command text. + SQL Server returned an error while executing the command text. -or- - + A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). An error occurred in a , or object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). The , or object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -2774,43 +2776,43 @@ The closed or dropped durin Sends the to the and builds a . A object. - property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call . - + property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call . + > [!NOTE] -> If a transaction is deadlocked, an exception may not be thrown until is called. - - The multiple active result set (MARS) feature allows for multiple actions using the same connection. - +> If a transaction is deadlocked, an exception may not be thrown until is called. + + The multiple active result set (MARS) feature allows for multiple actions using the same connection. + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - - - -## Examples - The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. - + + + +## Examples + The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteReader Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteReader Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteReader Example/VB/source.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . + A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. + An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. -or- A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - The current state of the connection is closed. requires an open . + The current state of the connection is closed. requires an open . -or- @@ -2863,33 +2865,33 @@ The closed or dropped durin Sends the to the , and builds a using one of the values. A object. - property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call . - + property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call . + > [!NOTE] -> Use to retrieve large values and binary data. Otherwise, an might occur and the connection will be closed. - - The multiple active result set (MARS) feature allows for multiple actions using the same connection. - +> Use to retrieve large values and binary data. Otherwise, an might occur and the connection will be closed. + + The multiple active result set (MARS) feature allows for multiple actions using the same connection. + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - - - -## Examples - The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. is set to . - + + + +## Examples + The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. is set to . + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteReader2/CS/mysample.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteReader2/VB/mysample.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteReader2/VB/mysample.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . + A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- @@ -2911,11 +2913,11 @@ The closed or dropped durin Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this . - ADO.NET Overview @@ -2956,35 +2958,35 @@ The closed or dropped durin An asynchronous version of , which sends the to the and builds a . Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . + A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . An invalid value. - Calling more than once for the same instance before task completion. + Calling more than once for the same instance before task completion. -or- - The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- is specified in the connection string. - SQL Server returned an error while executing the command text. + SQL Server returned an error while executing the command text. -or- @@ -3032,35 +3034,35 @@ The closed or dropped durin An asynchronous version of , which sends the to the , and builds a . Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- - A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . + A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . An invalid value. - Calling more than once for the same instance before task completion. + Calling more than once for the same instance before task completion. -or- - The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- is specified in the connection string. - SQL Server returned an error while executing the command text. + SQL Server returned an error while executing the command text. -or- @@ -3105,40 +3107,40 @@ The closed or dropped durin The cancellation instruction. - An asynchronous version of , which sends the to the and builds a . - + An asynchronous version of , which sends the to the and builds a . + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- - + A other than **Xml** was used when was set to . An invalid value. - Calling more than once for the same instance before task completion. + Calling more than once for the same instance before task completion. -or- -The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). +The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- is specified in the connection string. - SQL Server returned an error while executing the command text. + SQL Server returned an error while executing the command text. -or- @@ -3146,6 +3148,7 @@ A timeout occurred during a streaming operation. For more information about stre An error occurred in a , or object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). The , or object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -3185,40 +3188,40 @@ A timeout occurred during a streaming operation. For more information about stre Options for statement execution and data retrieval. When is set to , reads the entire row before returning a complete Task. The cancellation instruction. - An asynchronous version of , which sends the to the , and builds a - + An asynchronous version of , which sends the to the , and builds a + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . An invalid value. - Calling more than once for the same instance before task completion. + Calling more than once for the same instance before task completion. -or- -The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). +The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- is specified in the connection string. - SQL Server returned an error while executing the command text. + SQL Server returned an error while executing the command text. -or- @@ -3226,6 +3229,7 @@ A timeout occurred during a streaming operation. For more information about stre An error occurred in a , or object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). The , or object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -3273,36 +3277,36 @@ A timeout occurred during a streaming operation. For more information about stre Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. The first column of the first row in the result set, or a null reference ( in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters. - method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the method, and then performing the operations that you need to generate the single value using the data returned by a . - - A typical query can be formatted as in the following C# example: - + method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the method, and then performing the operations that you need to generate the single value using the data returned by a . + + A typical query can be formatted as in the following C# example: + ```csharp -cmd.CommandText = "SELECT COUNT(*) FROM dbo.region"; -Int32 count = (Int32) cmd.ExecuteScalar(); -``` - -## Examples - The following example creates a and then executes it using . The example is passed a string representing a new value to be inserted into a table, and a string to use to connect to the data source. The function returns the new **Identity** column value if a new row was inserted, 0 on failure. - +cmd.CommandText = "SELECT COUNT(*) FROM dbo.region"; +Int32 count = (Int32) cmd.ExecuteScalar(); +``` + +## Examples + The following example creates a and then executes it using . The example is passed a string representing a new value to be inserted into a table, and a string to use to connect to the data source. The function returns the new **Identity** column value if a new row was inserted, 0 on failure. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/VB/source.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. + An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. -or- @@ -3349,39 +3353,39 @@ A timeout occurred during a streaming operation. For more information about stre The cancellation instruction. - An asynchronous version of , which executes the query asynchronously and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. - + An asynchronous version of , which executes the query asynchronously and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Calling more than once for the same instance before task completion. + Calling more than once for the same instance before task completion. -or- -The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). +The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- is specified in the connection string. - SQL Server returned an error while executing the command text. + SQL Server returned an error while executing the command text. -or- @@ -3389,6 +3393,7 @@ A timeout occurred during a streaming operation. For more information about stre An error occurred in a , or object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). The , or object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -3428,44 +3433,44 @@ A timeout occurred during a streaming operation. For more information about stre Sends the to the and builds an object. An object. - property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, can also specify a statement that returns `ntext` or `nvarchar` data that contains valid XML, or the contents of a column defined with the `xml` data type. - - A typical query can be formatted as in the following Microsoft Visual C# example: - + The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, can also specify a statement that returns `ntext` or `nvarchar` data that contains valid XML, or the contents of a column defined with the `xml` data type. + + A typical query can be formatted as in the following Microsoft Visual C# example: + ```csharp -SqlCommand command = new SqlCommand("SELECT * FROM dbo.Customers FOR XML AUTO, XMLDATA", SqlConn); -``` - - This method can also be used to retrieve a single-row, single-column result set that contains XML data. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. - - The multiple active result set (MARS) feature allows for multiple actions using the same connection. - +SqlCommand command = new SqlCommand("SELECT * FROM dbo.Customers FOR XML AUTO, XMLDATA", SqlConn); +``` + + This method can also be used to retrieve a single-row, single-column result set that contains XML data. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. + + The multiple active result set (MARS) feature allows for multiple actions using the same connection. + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. -## Examples - The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL FOR XML SELECT statement, and a string to use to connect to the data source. - +## Examples + The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL FOR XML SELECT statement, and a string to use to connect to the data source. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteXmlReader/CS/mysample.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteXmlReader/VB/mysample.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteXmlReader/VB/mysample.vb" id="Snippet1"::: + ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. + An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. -or- @@ -3520,42 +3525,42 @@ A timeout occurred during a streaming operation. For more information about stre - An asynchronous version of , which sends the to the and builds an object. - + An asynchronous version of , which sends the to the and builds an object. + Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Calling more than once for the same instance before task completion. + Calling more than once for the same instance before task completion. -or- -The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). +The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- is specified in the connection string. - SQL Server returned an error while executing the command text. + SQL Server returned an error while executing the command text. -or- @@ -3600,42 +3605,42 @@ A timeout occurred during a streaming operation. For more information about stre The cancellation instruction. - An asynchronous version of , which sends the to the and builds an object. - + An asynchronous version of , which sends the to the and builds an object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + A other than **Binary** or **VarBinary** was used when was set to . For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- -A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . +A other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when was set to . -or- A other than **Xml** was used when was set to . - Calling more than once for the same instance before task completion. + Calling more than once for the same instance before task completion. -or- -The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). +The closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). -or- is specified in the connection string. - SQL Server returned an error while executing the command text. + SQL Server returned an error while executing the command text. -or- @@ -3643,6 +3648,7 @@ A timeout occurred during a streaming operation. For more information about stre An error occurred in a , or object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). The , or object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -3685,11 +3691,11 @@ A timeout occurred during a streaming operation. For more information about stre Gets or sets a value that specifies the object bound to this command. When set to null (default), no notification should be requested. - Using Query Notifications @@ -3729,13 +3735,13 @@ A timeout occurred during a streaming operation. For more information about stre if the application should automatically receive query notifications; otherwise . The default value is . - Using Query Notifications @@ -3790,24 +3796,24 @@ A timeout occurred during a streaming operation. For more information about stre Gets the . The parameters of the Transact-SQL statement or stored procedure. The default is an empty collection. - [!NOTE] -> If the parameters in the collection do not match the requirements of the query to be executed, an error may result. - - For more information, see [Configuring Parameters and Parameter Data Types](/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types). - -## Examples - The following example demonstrates how to create a and add parameters to the . - +> If the parameters in the collection do not match the requirements of the query to be executed, an error may result. + + For more information, see [Configuring Parameters and Parameter Data Types](/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types). + +## Examples + The following example demonstrates how to create a and add parameters to the . + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlParameterCollection.AddWithValue/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlParameterCollection.AddWithValue/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlParameterCollection.AddWithValue/VB/source.vb" id="Snippet1"::: + ]]> Connecting and Retrieving Data in ADO.NET @@ -3859,28 +3865,28 @@ A timeout occurred during a streaming operation. For more information about stre Creates a prepared version of the command on an instance of SQL Server. - is set to `StoredProcedure`, the call to should succeed, although it may cause a no-op. - - Before you call , specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable length data type, you must set the property to the maximum size needed. returns an error if these conditions are not met. - + is set to `StoredProcedure`, the call to should succeed, although it may cause a no-op. + + Before you call , specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable length data type, you must set the property to the maximum size needed. returns an error if these conditions are not met. + > [!NOTE] -> If the database context is changed by executing the Transact-SQL `USE ` statement, or by calling the method, then must be called a second time. - - If you call an `Execute` method after calling , any parameter value that is larger than the value specified by the property is automatically truncated to the original specified size of the parameter, and no truncation errors are returned. - - Output parameters (whether prepared or not) must have a user-specified data type. If you specify a variable length data type, you must also specify the maximum . - - Prior to Visual Studio 2010, threw an exception. Beginning in Visual Studio 2010, this method does not throw an exception. - -## Examples - The following example demonstrates the use of the method. - +> If the database context is changed by executing the Transact-SQL `USE ` statement, or by calling the method, then must be called a second time. + + If you call an `Execute` method after calling , any parameter value that is larger than the value specified by the property is automatically truncated to the original specified size of the parameter, and no truncation errors are returned. + + Output parameters (whether prepared or not) must have a user-specified data type. If you specify a variable length data type, you must also specify the maximum . + + Prior to Visual Studio 2010, threw an exception. Beginning in Visual Studio 2010, this method does not throw an exception. + +## Examples + The following example demonstrates the use of the method. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.Prepare/CS/Source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.Prepare/VB/Source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlCommand.Prepare/VB/Source.vb" id="Snippet1"::: + ]]> Connecting and Retrieving Data in ADO.NET @@ -3919,11 +3925,11 @@ A timeout occurred during a streaming operation. For more information about stre Resets the property to its default value. - is 30 seconds. - + is 30 seconds. + ]]> Connecting and Retrieving Data in ADO.NET @@ -4159,11 +4165,11 @@ This member is an explicit interface member implementation. It can be used only Gets or sets the within which the executes. The . The default value is . - property if it is already set to a specific value, and the command is in the process of executing. If you set the transaction property to a object that is not connected to the same as the object, an exception is thrown the next time that you attempt to execute a statement. - + property if it is already set to a specific value, and the command is in the process of executing. If you set the transaction property to a object that is not connected to the same as the object, an exception is thrown the next time that you attempt to execute a statement. + ]]> Performing a Transaction @@ -4224,13 +4230,13 @@ This member is an explicit interface member implementation. It can be used only Gets or sets how command results are applied to the when used by the **Update** method of the . One of the values. - value is **Both** unless the command is automatically generated (as in the case of the ), in which case the default is **None**. - - For more information about using the **UpdatedRowSource** property, see [DataAdapter Parameters](/dotnet/framework/data/adonet/dataadapter-parameters). - + value is **Both** unless the command is automatically generated (as in the case of the ), in which case the default is **None**. + + For more information about using the **UpdatedRowSource** property, see [DataAdapter Parameters](/dotnet/framework/data/adonet/dataadapter-parameters). + ]]> Connecting and Retrieving Data in ADO.NET diff --git a/xml/System.Data.SqlClient/SqlConnection.xml b/xml/System.Data.SqlClient/SqlConnection.xml index c7483c0c054..cf985794fea 100644 --- a/xml/System.Data.SqlClient/SqlConnection.xml +++ b/xml/System.Data.SqlClient/SqlConnection.xml @@ -2633,6 +2633,7 @@ class Program { A connection was not available from the connection pool before the connection time out elapsed. Any error returned by SQL Server that occurred while opening the connection. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Data.SqlClient/SqlDataReader.xml b/xml/System.Data.SqlClient/SqlDataReader.xml index aeee87a5d53..1538f7e8431 100644 --- a/xml/System.Data.SqlClient/SqlDataReader.xml +++ b/xml/System.Data.SqlClient/SqlDataReader.xml @@ -63,30 +63,30 @@ Provides a way of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited. - , you must call the method of the object, instead of directly using a constructor. - - While the is being used, the associated is busy serving the , and no other operations can be performed on the other than closing it. This is the case until the method of the is called. For example, you cannot retrieve output parameters until after you call . - - Changes made to a result set by another process or thread while data is being read may be visible to the user of the `SqlDataReader`. However, the precise behavior is timing dependent. - - and are the only properties that you can call after the is closed. Although the property may be accessed while the exists, always call before returning the value of to guarantee an accurate return value. - - When using sequential access (), an will be raised if the position is advanced and another read operation is attempted on the previous column. - + , you must call the method of the object, instead of directly using a constructor. + + While the is being used, the associated is busy serving the , and no other operations can be performed on the other than closing it. This is the case until the method of the is called. For example, you cannot retrieve output parameters until after you call . + + Changes made to a result set by another process or thread while data is being read may be visible to the user of the `SqlDataReader`. However, the precise behavior is timing dependent. + + and are the only properties that you can call after the is closed. Although the property may be accessed while the exists, always call before returning the value of to guarantee an accurate return value. + + When using sequential access (), an will be raised if the position is advanced and another read operation is attempted on the previous column. + > [!NOTE] -> For optimal performance, avoids creating unnecessary objects or making unnecessary copies of data. Therefore, multiple calls to methods such as return a reference to the same object. Use caution if you are modifying the underlying value of the objects returned by methods such as . - - - -## Examples - The following example creates a , a , and a . The example reads through the data, writing it out to the console window. The code then closes the . The is closed automatically at the end of the `using` code block. - +> For optimal performance, avoids creating unnecessary objects or making unnecessary copies of data. Therefore, multiple calls to methods such as return a reference to the same object. Use caution if you are modifying the underlying value of the objects returned by methods such as . + + + +## Examples + The following example creates a , a , and a . The example reads through the data, writing it out to the console window. The code then closes the . The is closed automatically at the end of the `using` code block. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/VB/source.vb" id="Snippet1"::: + ]]> DataAdapters and DataReaders @@ -128,24 +128,24 @@ Closes the object. - method when you are through using the to use the associated for any other purpose. - - The `Close` method fills in the values for output parameters, return values and `RecordsAffected`, increasing the time that it takes to close a `SqlDataReader` that was used to process a large or complex query. When the return values and the number of records affected by a query are not significant, the time that it takes to close the `SqlDataReader` can be reduced by calling the method of the associated object before calling the `Close` method. - + method when you are through using the to use the associated for any other purpose. + + The `Close` method fills in the values for output parameters, return values and `RecordsAffected`, increasing the time that it takes to close a `SqlDataReader` that was used to process a large or complex query. When the return values and the number of records affected by a query are not significant, the time that it takes to close the `SqlDataReader` can be reduced by calling the method of the associated object before calling the `Close` method. + > [!CAUTION] -> Do not call `Close` or `Dispose` on a Connection, a DataReader, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/). - - - -## Examples - The following example creates a , a `SqlCommand`, and a . The example reads through the data, writing it out to the console window. The code then closes the . The is closed automatically at the end of the `using` code block. - +> Do not call `Close` or `Dispose` on a Connection, a DataReader, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/). + + + +## Examples + The following example creates a , a `SqlCommand`, and a . The example reads through the data, writing it out to the console window. The code then closes the . The is closed automatically at the end of the `using` code block. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Close Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Close Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Close Example/VB/source.vb" id="Snippet1"::: + ]]> DataAdapters and DataReaders @@ -237,11 +237,11 @@ Gets a value that indicates the depth of nesting for the current row. The depth of nesting for the current row. - DataAdapters and DataReaders (ADO.NET) @@ -291,11 +291,11 @@ Gets the number of columns in the current row. When not positioned in a valid recordset, 0; otherwise the number of columns in the current row. The default is -1. - to 0. However. this should not be confused with a query that returns 0 rows (such as SELECT * FROM *table* WHERE 1 = 2) in which case returns the number of columns in the table, including hidden fields. Use to exclude hidden fields. - + to 0. However. this should not be confused with a query that returns 0 rows (such as SELECT * FROM *table* WHERE 1 = 2) in which case returns the number of columns in the table, including hidden fields. Use to exclude hidden fields. + ]]> There is no current connection to an instance of SQL Server. @@ -352,13 +352,13 @@ Gets the value of the specified column as a Boolean. The value of the column. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -415,13 +415,13 @@ Gets the value of the specified column as a byte. The value of the specified column as a byte. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -486,15 +486,15 @@ Reads a stream of bytes from the specified column offset into the buffer an array starting at the given buffer offset. The actual number of bytes read. - returns the number of available bytes in the field. Most of the time this is the exact length of the field. However, the number returned may be less than the true length of the field if `GetBytes` has already been used to obtain bytes from the field. This may be the case, for example, if the is reading a large data structure into a buffer. For more information, see the `SequentialAccess` setting for . - - If you pass a buffer that is `null`, returns the length of the entire field in bytes, not the remaining size based on the buffer offset parameter. - - No conversions are performed; therefore, the data retrieved must already be a byte array. - + returns the number of available bytes in the field. Most of the time this is the exact length of the field. However, the number returned may be less than the true length of the field if `GetBytes` has already been used to obtain bytes from the field. This may be the case, for example, if the is reading a large data structure into a buffer. For more information, see the `SequentialAccess` setting for . + + If you pass a buffer that is `null`, returns the length of the entire field in bytes, not the remaining size based on the buffer offset parameter. + + No conversions are performed; therefore, the data retrieved must already be a byte array. + ]]> DataAdapters and DataReaders (ADO.NET) @@ -556,11 +556,11 @@ Gets the value of the specified column as a single character. The value of the specified column. - . - + . + ]]> The specified cast is not valid. @@ -623,18 +623,18 @@ Reads a stream of characters from the specified column offset into the buffer as an array starting at the given buffer offset. The actual number of characters read. - returns the number of available characters in the field. Frequently this is the exact length of the field. However, the number returned may be less than the true length of the field if `GetChars` has already been used to obtain characters from the field. This may be the case, for example, if the is reading a large data structure into a buffer. For more information, see the `SequentialAccess` setting for . - - The actual number of characters read can be less than the requested length, if the end of the field is reached. If you pass a buffer that is `null`, returns the length of the entire field in characters, not the remaining size based on the buffer offset parameter. - - No conversions are performed; therefore. the data retrieved must already be a character array. - + returns the number of available characters in the field. Frequently this is the exact length of the field. However, the number returned may be less than the true length of the field if `GetChars` has already been used to obtain characters from the field. This may be the case, for example, if the is reading a large data structure into a buffer. For more information, see the `SequentialAccess` setting for . + + The actual number of characters read can be less than the requested length, if the end of the field is reached. If you pass a buffer that is `null`, returns the length of the entire field in characters, not the remaining size based on the buffer offset parameter. + + No conversions are performed; therefore. the data retrieved must already be a character array. + > [!NOTE] -> The method returns 0 when `dataIndex` is negative. - +> The method returns 0 when `dataIndex` is negative. + ]]> DataAdapters and DataReaders (ADO.NET) @@ -671,7 +671,7 @@ The read-only column schema collection. method, which enables the use of the interface to populate the schema metadata without using a . @@ -765,13 +765,13 @@ This method is an implementation of Gets a string representing the data type of the specified column. The string representing the data type of the specified column. - ADO.NET Overview @@ -825,13 +825,13 @@ This method is an implementation of Gets the value of the specified column as a object. The value of the specified column. - object. - - Call to check for null values before calling this method. - + object. + + Call to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -879,13 +879,13 @@ This method is an implementation of Retrieves the value of the specified column as a object. The value of the specified column. - object. - - Call to check for null values before calling this method. - + object. + + Call to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -943,13 +943,13 @@ This method is an implementation of Gets the value of the specified column as a object. The value of the specified column. - object. - - Call to check for null values before calling this method. - + object. + + Call to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -1006,13 +1006,13 @@ This method is an implementation of Gets the value of the specified column as a double-precision floating point number. The value of the specified column. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -1057,11 +1057,11 @@ This method is an implementation of Returns an that iterates through the . An for the . - DataAdapters and DataReaders (ADO.NET) @@ -1122,7 +1122,7 @@ This method is an implementation of instance is cast to an interface. - + This information can be used to increase performance by indicating the strongly-typed accessor to call. (for example, using `GetInt32` is roughly ten times faster than using `GetValue`.) ]]> @@ -1174,33 +1174,33 @@ This member is an explicit interface member implementation. It can be used only Synchronously gets the value of the specified column as a type. is the asynchronous version of this method. The returned type object. - .||| - - For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - + .||| + + For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + ]]> - The connection drops or is closed during the data retrieval. - - The is closed during the data retrieval. - - There is no data ready to be read (for example, the first hasn't been called, or returned false). - - Tried to read a previously-read column in sequential mode. - + The connection drops or is closed during the data retrieval. + + The is closed during the data retrieval. + + There is no data ready to be read (for example, the first hasn't been called, or returned false). + + Tried to read a previously-read column in sequential mode. + There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. Trying to read a column that does not exist. The value of the column was null ( == ), retrieving a non-SQL type. @@ -1252,40 +1252,41 @@ This member is an explicit interface member implementation. It can be used only Asynchronously gets the value of the specified column as a type. is the synchronous version of this method. The returned type object. - .||| - - For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - + .||| + + For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + ]]> - The connection drops or is closed during the data retrieval. - - The is closed during the data retrieval. - - There is no data ready to be read (for example, the first hasn't been called, or returned false). - - Tried to read a previously-read column in sequential mode. - - There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. - + The connection drops or is closed during the data retrieval. + + The is closed during the data retrieval. + + There is no data ready to be read (for example, the first hasn't been called, or returned false). + + Tried to read a previously-read column in sequential mode. + + There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. + is specified in the connection string. Trying to read a column that does not exist. The value of the column was null ( == ), retrieving a non-SQL type. doesn't match the type returned by SQL Server or cannot be cast. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1336,13 +1337,13 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a single-precision floating point number. The value of the specified column. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -1399,13 +1400,13 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a globally unique identifier (GUID). The value of the specified column. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -1462,13 +1463,13 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a 16-bit signed integer. The value of the specified column. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -1525,13 +1526,13 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a 32-bit signed integer. The value of the specified column. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -1588,13 +1589,13 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a 64-bit signed integer. The value of the specified column. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -1704,23 +1705,23 @@ This member is an explicit interface member implementation. It can be used only Gets the column ordinal, given the name of the column. The zero-based column ordinal. - method. - + method. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.GetOrdinal/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.GetOrdinal/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.GetOrdinal/VB/source.vb" id="Snippet1"::: + ]]> The name specified is not a valid column name. @@ -1903,47 +1904,47 @@ This member is an explicit interface member implementation. It can be used only Returns a that describes the column metadata of the . A that describes the column metadata. - method returns the following metadata about each column: - -|DataReader column|Description| -|-----------------------|-----------------| -|AllowDBNull|Set if the consumer can set the column to a null value or if the provider cannot determine whether the consumer can set the column to a null value. Otherwise, not set. A column may contain null values, even if it cannot be set to a null value.| -|BaseCatalogName|The name of the catalog in the data store that contains the column. NULL if the base catalog name cannot be determined. The default of this column is a null value.| -|BaseColumnName|The name of the column in the data store. This might be different than the column name returned in the ColumnName column if an alias was used. A null value if the base column name cannot be determined or if the rowset column is derived, but not identical to, a column in the data store. The default of this column is a null value.| -|BaseSchemaName|The name of the schema in the data store that contains the column. A null value if the base schema name cannot be determined. The default of this column is a null value.| -|BaseServerName|The name of the instance of Microsoft SQL Server used by the .| -|BaseTableName|The name of the table or view in the data store that contains the column. A null value if the base table name cannot be determined. The default of this column is a null value.| -|ColumnName|The name of the column; this might not be unique. If this cannot be determined, a null value is returned. This name always reflects the most recent renaming of the column in the current view or command text.| -|ColumnOrdinal|The zero-based ordinal of the column. This column cannot contain a null value.| + method returns the following metadata about each column: + +|DataReader column|Description| +|-----------------------|-----------------| +|AllowDBNull|Set if the consumer can set the column to a null value or if the provider cannot determine whether the consumer can set the column to a null value. Otherwise, not set. A column may contain null values, even if it cannot be set to a null value.| +|BaseCatalogName|The name of the catalog in the data store that contains the column. NULL if the base catalog name cannot be determined. The default of this column is a null value.| +|BaseColumnName|The name of the column in the data store. This might be different than the column name returned in the ColumnName column if an alias was used. A null value if the base column name cannot be determined or if the rowset column is derived, but not identical to, a column in the data store. The default of this column is a null value.| +|BaseSchemaName|The name of the schema in the data store that contains the column. A null value if the base schema name cannot be determined. The default of this column is a null value.| +|BaseServerName|The name of the instance of Microsoft SQL Server used by the .| +|BaseTableName|The name of the table or view in the data store that contains the column. A null value if the base table name cannot be determined. The default of this column is a null value.| +|ColumnName|The name of the column; this might not be unique. If this cannot be determined, a null value is returned. This name always reflects the most recent renaming of the column in the current view or command text.| +|ColumnOrdinal|The zero-based ordinal of the column. This column cannot contain a null value.| |ColumnSize|The maximum possible length of a value in the column. For columns that use a fixed-length data type, this is the size of the data type. For `nvarchar(MAX)`, `varchar(MAX)`, and `varbinary(MAX)` columns stored in a SQL Server database, the maximum size is 2GB. If these columns are stored and accessed as files, the limit on maximum size is imposed by the file system. This value changes when using the `Type System Version` keyword in the connection string. For new types they are represented as downlevel types. The MAX data types return the normal 4k for `nvarchar` and 8000 for `varchar`. For more information, see the [Transact-SQL reference](/sql/t-sql/language-reference).| -|DataTypeName|Returns a string representing the data type of the specified column.| -|IsAliased|`true`: The column name is an alias.

`false`: The column name is not an alias.| -|IsAutoIncrement|`true`: The column assigns values to new rows in fixed increments.

`false`: The column does not assign values to new rows in fixed increments. The default of this column is `false`.| -|IsColumnSet|`true`: The column is a sparse column that is a member of a column set.| -|IsExpression|`true`: The column is an expression.

`false`: The column is not an expression.| -|IsHidden|`true`: The column is hidden.

`false`: The column is not hidden.| -|IsIdentity|`true`: The column is an identity column.

`false`: The column is not an identity column.| -|IsKey|`true`: The column is one of a set of columns in the rowset that, taken together, uniquely identify the row. The set of columns with `IsKey` set to `true` must uniquely identify a row in the rowset. There is no requirement that this set of columns is a minimal set of columns. This set of columns may be generated from a base table primary key, a unique constraint or a unique index.

`false`: The column is not required to uniquely identify the row.| -|IsLong|`true`: The column contains a Binary Long Object (BLOB) that contains very long data. The definition of very long data is provider-specific.

`false`: The column does not contain a Binary Long Object (BLOB) that contains very long data.| -|IsReadOnly|`true`: The column cannot be modified.

`false`: The column can be modified.| -|IsRowVersion|`true`: The column contains a persistent row identifier that cannot be written to, and has no meaningful value except to identity the row.

`false`: The column does not contain a persistent row identifier that cannot be written to, and has no meaningful value except to identity the row.| -|IsUnique|`true`: Column is of type `timestamp`.

`false`: Column is not of type `timestamp`.| -|NonVersionedProviderType|The type of the column irrespective of the current `Type System Version` specified in the connection string. The returned value is from the enumeration.| -|NumericPrecision|If `ProviderType` is a numeric data type, this is the maximum precision of the column. The precision depends on the definition of the column. If `ProviderType` is not a numeric data type, this is 255.| -|NumericScale|If `ProviderType` is DBTYPE_DECIMAL or DBTYPE_NUMERIC, the number of digits to the right of the decimal point. Otherwise, this is 255.| -|ProviderSpecificDataType|Returns the provider-specific data type of the column based on the `Type System Version` keyword in the connection string.| -|ProviderType|The indicator of the column's data type. If the data type of the column varies from row to row, this must be Object. This column cannot contain a null value.| -|UdtAssemblyQualifiedName|If the column is a user-defined type (UDT), this is the qualified name of the UDT's assembly as per . If the column is not a UDT, this is null.| -|XmlSchemaCollectionDatabase|The name of the database where the schema collection for this XML instance is located, if the row contains information about an XML column. This value is `null` (`Nothing` in Visual Basic) if the collection is defined within the current database. It is also null if there is no schema collection, in which case the `XmlSchemaCollectionName` and `XmlSchemaCollectionOwningSchema` columns are also null.| -|XmlSchemaCollectionName|The name of the schema collection for this XML instance, if the row contains information about an XML column. This value is `null` (`Nothing` in Visual Basic) if there is no associated schema collection. If the value is null, the `XmlSchemaCollectionDatabase` and `XmlSchemaCollectionOwningSchema` columns are also null.| -|XmlSchemaCollectionOwningSchema|The owning relational schema where the schema collection for this XML instance is located, if the row contains information about an XML column. This value is `null` (`Nothing` in Visual Basic) if the collection is defined within the current database. It is also null if there is no schema collection, in which case the `XmlSchemaCollectionDatabase` and `XmlSchemaCollectionName` columns are also null.| - +|DataTypeName|Returns a string representing the data type of the specified column.| +|IsAliased|`true`: The column name is an alias.

`false`: The column name is not an alias.| +|IsAutoIncrement|`true`: The column assigns values to new rows in fixed increments.

`false`: The column does not assign values to new rows in fixed increments. The default of this column is `false`.| +|IsColumnSet|`true`: The column is a sparse column that is a member of a column set.| +|IsExpression|`true`: The column is an expression.

`false`: The column is not an expression.| +|IsHidden|`true`: The column is hidden.

`false`: The column is not hidden.| +|IsIdentity|`true`: The column is an identity column.

`false`: The column is not an identity column.| +|IsKey|`true`: The column is one of a set of columns in the rowset that, taken together, uniquely identify the row. The set of columns with `IsKey` set to `true` must uniquely identify a row in the rowset. There is no requirement that this set of columns is a minimal set of columns. This set of columns may be generated from a base table primary key, a unique constraint or a unique index.

`false`: The column is not required to uniquely identify the row.| +|IsLong|`true`: The column contains a Binary Long Object (BLOB) that contains very long data. The definition of very long data is provider-specific.

`false`: The column does not contain a Binary Long Object (BLOB) that contains very long data.| +|IsReadOnly|`true`: The column cannot be modified.

`false`: The column can be modified.| +|IsRowVersion|`true`: The column contains a persistent row identifier that cannot be written to, and has no meaningful value except to identity the row.

`false`: The column does not contain a persistent row identifier that cannot be written to, and has no meaningful value except to identity the row.| +|IsUnique|`true`: Column is of type `timestamp`.

`false`: Column is not of type `timestamp`.| +|NonVersionedProviderType|The type of the column irrespective of the current `Type System Version` specified in the connection string. The returned value is from the enumeration.| +|NumericPrecision|If `ProviderType` is a numeric data type, this is the maximum precision of the column. The precision depends on the definition of the column. If `ProviderType` is not a numeric data type, this is 255.| +|NumericScale|If `ProviderType` is DBTYPE_DECIMAL or DBTYPE_NUMERIC, the number of digits to the right of the decimal point. Otherwise, this is 255.| +|ProviderSpecificDataType|Returns the provider-specific data type of the column based on the `Type System Version` keyword in the connection string.| +|ProviderType|The indicator of the column's data type. If the data type of the column varies from row to row, this must be Object. This column cannot contain a null value.| +|UdtAssemblyQualifiedName|If the column is a user-defined type (UDT), this is the qualified name of the UDT's assembly as per . If the column is not a UDT, this is null.| +|XmlSchemaCollectionDatabase|The name of the database where the schema collection for this XML instance is located, if the row contains information about an XML column. This value is `null` (`Nothing` in Visual Basic) if the collection is defined within the current database. It is also null if there is no schema collection, in which case the `XmlSchemaCollectionName` and `XmlSchemaCollectionOwningSchema` columns are also null.| +|XmlSchemaCollectionName|The name of the schema collection for this XML instance, if the row contains information about an XML column. This value is `null` (`Nothing` in Visual Basic) if there is no associated schema collection. If the value is null, the `XmlSchemaCollectionDatabase` and `XmlSchemaCollectionOwningSchema` columns are also null.| +|XmlSchemaCollectionOwningSchema|The owning relational schema where the schema collection for this XML instance is located, if the row contains information about an XML column. This value is `null` (`Nothing` in Visual Basic) if the collection is defined within the current database. It is also null if there is no schema collection, in which case the `XmlSchemaCollectionDatabase` and `XmlSchemaCollectionName` columns are also null.| + > [!NOTE] -> To make sure that metadata columns return the correct information, you must call with the `behavior` parameter set to `KeyInfo`. Otherwise, some of the columns in the schema table may return default, null, or incorrect data. - +> To make sure that metadata columns return the correct information, you must call with the `behavior` parameter set to `KeyInfo`. Otherwise, some of the columns in the schema table may return default, null, or incorrect data. + ]]>
The is closed. @@ -1995,11 +1996,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2053,11 +2054,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column. - SQL Server Data Types and ADO.NET @@ -2111,11 +2112,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2259,11 +2260,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2317,11 +2318,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2375,11 +2376,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2433,11 +2434,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2491,11 +2492,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2549,11 +2550,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2607,11 +2608,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2665,11 +2666,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2723,11 +2724,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2781,11 +2782,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a . The value of the column expressed as a . - SQL Server Data Types and ADO.NET @@ -2839,11 +2840,11 @@ This member is an explicit interface member implementation. It can be used only Returns the data value in the specified column as a SQL Server type. The value of the column expressed as a . - returns data using the native SQL Server types. To retrieve data using the .NET Framework types, see . - + returns data using the native SQL Server types. To retrieve data using the .NET Framework types, see . + ]]> SQL Server Data Types and ADO.NET @@ -2897,11 +2898,11 @@ This member is an explicit interface member implementation. It can be used only Fills an array of that contains the values for all the columns in the record, expressed as SQL Server types. An integer indicating the number of columns copied. - array does not need to match the number of columns in the record. You can pass an array that contains fewer than the number of columns contained in the record. Only the amount of data the array holds is copied to the array, starting at the column with ordinal 0. You can also pass an array whose length is more than the number of columns contained in the resulting row. Any remaining columns are untouched. - + array does not need to match the number of columns in the record. You can pass an array that contains fewer than the number of columns contained in the record. Only the amount of data the array holds is copied to the array, starting at the column with ordinal 0. You can also pass an array whose length is more than the number of columns contained in the resulting row. Any remaining columns are untouched. + ]]> @@ -2951,13 +2952,13 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as an XML value. A value that contains the XML stored within the corresponding field. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The index passed was outside the range of 0 to - 1 @@ -3007,61 +3008,61 @@ This member is an explicit interface member implementation. It can be used only Retrieves binary, image, varbinary, UDT, and variant data types as a . A stream object. - defaults to the value of ; but you can modify via . - - Null values will be returned as an empty (zero bytes) . - - will raise an exception when used on an object returned by when is in effect. - - exceptions raised from are thrown as exceptions; check the inner exception for the . - - The following members are not available for objects returned by : - -- BeginWrite - -- EndWrite - -- Length - -- Position - -- Seek - -- SetLength - -- Write - -- WriteByte - -- WriteTimeout - - When the connection property `ContextConnection=true`, only supports synchronous data retrieval for both sequential () and non-sequential () access. - - For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - + defaults to the value of ; but you can modify via . + + Null values will be returned as an empty (zero bytes) . + + will raise an exception when used on an object returned by when is in effect. + + exceptions raised from are thrown as exceptions; check the inner exception for the . + + The following members are not available for objects returned by : + +- BeginWrite + +- EndWrite + +- Length + +- Position + +- Seek + +- SetLength + +- Write + +- WriteByte + +- WriteTimeout + + When the connection property `ContextConnection=true`, only supports synchronous data retrieval for both sequential () and non-sequential () access. + + For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + ]]> - The connection drops or is closed during the data retrieval. - - The is closed during the data retrieval. - - There is no data ready to be read (for example, the first hasn't been called, or returned false). - - Tried to read a previously-read column in sequential mode. - + The connection drops or is closed during the data retrieval. + + The is closed during the data retrieval. + + There is no data ready to be read (for example, the first hasn't been called, or returned false). + + Tried to read a previously-read column in sequential mode. + There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. Trying to read a column that does not exist. - The returned type was not one of the types below: - -- binary - -- image - -- varbinary - + The returned type was not one of the types below: + +- binary + +- image + +- varbinary + - udt
@@ -3114,13 +3115,13 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column as a string. The value of the specified column. - to check for null values before calling this method. - + to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -3168,43 +3169,43 @@ This member is an explicit interface member implementation. It can be used only Retrieves Char, NChar, NText, NVarChar, text, varChar, and Variant data types as a . The returned object. - exceptions raised from are thrown as exceptions; check the inner exception for the . - - Null values will be returned as an empty (zero bytes) . - - will raise an exception when used on an object returned by when is in effect. - - When the connection property `ContextConnection=true`, only supports synchronous data retrieval for both sequential () and non-sequential () access. - - For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - + exceptions raised from are thrown as exceptions; check the inner exception for the . + + Null values will be returned as an empty (zero bytes) . + + will raise an exception when used on an object returned by when is in effect. + + When the connection property `ContextConnection=true`, only supports synchronous data retrieval for both sequential () and non-sequential () access. + + For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + ]]> - The connection drops or is closed during the data retrieval. - - The is closed during the data retrieval. - - There is no data ready to be read (for example, the first hasn't been called, or returned false). - - Tried to read a previously-read column in sequential mode. - + The connection drops or is closed during the data retrieval. + + The is closed during the data retrieval. + + There is no data ready to be read (for example, the first hasn't been called, or returned false). + + Tried to read a previously-read column in sequential mode. + There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. Trying to read a column that does not exist. - The returned type was not one of the types below: - -- char - -- nchar - -- ntext - -- nvarchar - -- text - + The returned type was not one of the types below: + +- char + +- nchar + +- ntext + +- nvarchar + +- text + - varchar @@ -3248,13 +3249,13 @@ This member is an explicit interface member implementation. It can be used only Retrieves the value of the specified column as a object. The value of the specified column. - object. - - Call to check for null values before calling this method. - + object. + + Call to check for null values before calling this method. + ]]> The specified cast is not valid. @@ -3312,11 +3313,11 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column in its native format. This method returns for null database columns. - returns data using the .NET Framework types. - + returns data using the .NET Framework types. + ]]> SQL Server Data Types and ADO.NET @@ -3373,23 +3374,23 @@ This member is an explicit interface member implementation. It can be used only Populates an array of objects with the column values of the current row. The number of instances of in the array. - array that contains fewer than the number of columns contained in the resulting row. Only the amount of data the array holds is copied to the array. You can also pass an array whose length is more than the number of columns contained in the resulting row. - - This method returns for null database columns. - - - -## Examples - The following example demonstrates using a correctly sized array to read all values from the current row in the supplied . In addition, the sample demonstrates using a fixed-sized array that could be either smaller or larger than the number of available columns. - + array that contains fewer than the number of columns contained in the resulting row. Only the amount of data the array holds is copied to the array. You can also pass an array whose length is more than the number of columns contained in the resulting row. + + This method returns for null database columns. + + + +## Examples + The following example demonstrates using a correctly sized array to read all values from the current row in the supplied . In addition, the sample demonstrates using a fixed-sized array that could be either smaller or larger than the number of available columns. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.GetValueObject/CS/source.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DataTableReader.GetValueObject/VB/source.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DataTableReader.GetValueObject/VB/source.vb" id="Snippet2"::: + ]]> SQL Server Data Types and ADO.NET @@ -3436,27 +3437,27 @@ This member is an explicit interface member implementation. It can be used only Retrieves data of type XML as an . The returned object. - object returned by does not support asynchronous operations. If you require asynchronous operations on an , cast the XML column to an NVARCHAR(MAX) on the server and use with . - - exceptions raised from are thrown as exceptions; check the inner exception for the . - - will raise an exception when used on an object returned by when is in effect. - - For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). - + object returned by does not support asynchronous operations. If you require asynchronous operations on an , cast the XML column to an NVARCHAR(MAX) on the server and use with . + + exceptions raised from are thrown as exceptions; check the inner exception for the . + + will raise an exception when used on an object returned by when is in effect. + + For more information, see [SqlClient Streaming Support](/dotnet/framework/data/adonet/sqlclient-streaming-support). + ]]> - The connection drops or is closed during the data retrieval. - - The is closed during the data retrieval. - - There is no data ready to be read (for example, the first hasn't been called, or returned false). - - Trying to read a previously read column in sequential mode. - + The connection drops or is closed during the data retrieval. + + The is closed during the data retrieval. + + There is no data ready to be read (for example, the first hasn't been called, or returned false). + + Trying to read a previously read column in sequential mode. + There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. Trying to read a column that does not exist. The returned type was not xml. @@ -3550,11 +3551,11 @@ This member is an explicit interface member implementation. It can be used only if the specified instance is closed; otherwise . - instance that is closed. - + instance that is closed. + ]]> SQL Server Connection Pooling (ADO.NET) @@ -3602,11 +3603,11 @@ This member is an explicit interface member implementation. It can be used only if the specified is true, otherwise. - ADO.NET Overview @@ -3661,14 +3662,14 @@ This member is an explicit interface member implementation. It can be used only if the specified column value is equivalent to ; otherwise . - , , and so on) to avoid raising an error. - + , , and so on) to avoid raising an error. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/sqldatareader_isdbnull/cs/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/sqldatareader_isdbnull/vb/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/sqldatareader_isdbnull/vb/source.vb" id="Snippet1"::: + ]]> DataAdapters and DataReaders (ADO.NET) @@ -3713,33 +3714,34 @@ This member is an explicit interface member implementation. It can be used only The zero-based column to be retrieved. The cancellation instruction, which propagates a notification that operations should be canceled. This does not guarantee the cancellation. A setting of makes this method equivalent to . The returned task must be marked as cancelled. - An asynchronous version of , which gets a value that indicates whether the column contains non-existent or missing values. - + An asynchronous version of , which gets a value that indicates whether the column contains non-existent or missing values. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. if the specified column value is equivalent to otherwise . - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - The connection drops or is closed during the data retrieval. - - The is closed during the data retrieval. - - There is no data ready to be read (for example, the first hasn't been called, or returned false). - - Trying to read a previously read column in sequential mode. - - There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. - + The connection drops or is closed during the data retrieval. + + The is closed during the data retrieval. + + There is no data ready to be read (for example, the first hasn't been called, or returned false). + + Trying to read a previously read column in sequential mode. + + There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. + is specified in the connection string. Trying to read a column that does not exist. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3850,13 +3852,13 @@ This member is an explicit interface member implementation. It can be used only Gets the value of the specified column in its native format given the column name. The value of the specified column in its native format. - No column with the specified name was found. @@ -3911,13 +3913,13 @@ This member is an explicit interface member implementation. It can be used only if there are more result sets; otherwise . - DataAdapters and DataReaders (ADO.NET) @@ -3959,25 +3961,26 @@ This member is an explicit interface member implementation. It can be used only The cancellation instruction. - An asynchronous version of , which advances the data reader to the next result, when reading the results of batch Transact-SQL statements. - + An asynchronous version of , which advances the data reader to the next result, when reading the results of batch Transact-SQL statements. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling more than once for the same instance before task completion. - + Calling more than once for the same instance before task completion. + is specified in the connection string. SQL Server returned an error while executing the command text. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -4026,21 +4029,21 @@ This member is an explicit interface member implementation. It can be used only if there are more rows; otherwise . - is before the first record. Therefore, you must call to begin accessing any data. - - Only one `SqlDataReader` per associated may be open at a time, and any attempt to open another will fail until the first one is closed. Similarly, while the `SqlDataReader` is being used, the associated `SqlConnection` is busy serving it until you call . - - - -## Examples - The following example creates a , a , and a . The example reads through the data, writing it out to the console window. The code then closes the . The is closed automatically at the end of the `using` code block. - + is before the first record. Therefore, you must call to begin accessing any data. + + Only one `SqlDataReader` per associated may be open at a time, and any attempt to open another will fail until the first one is closed. Similarly, while the `SqlDataReader` is being used, the associated `SqlConnection` is busy serving it until you call . + + + +## Examples + The following example creates a , a , and a . The example reads through the data, writing it out to the console window. The code then closes the . The is closed automatically at the end of the `using` code block. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/CS/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/VB/source.vb" id="Snippet1"::: + ]]> SQL Server returned an error while executing the command text. @@ -4084,27 +4087,28 @@ This member is an explicit interface member implementation. It can be used only The cancellation instruction. - An asynchronous version of , which advances the to the next record. - + An asynchronous version of , which advances the to the next record. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. A task representing the asynchronous operation. - is set to `Default`, reads the entire row before returning the Task. - - For more information, including code samples, about asynchronous programming in the .NET Framework Data Provider for SQL Server, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). - + is set to `Default`, reads the entire row before returning the Task. + + For more information, including code samples, about asynchronous programming in the .NET Framework Data Provider for SQL Server, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - Calling more than once for the same instance before task completion. - + Calling more than once for the same instance before task completion. + is specified in the connection string. SQL Server returned an error while executing the command text. ADO.NET Overview + The cancellation token was canceled. This exception is stored into the returned task. @@ -4149,13 +4153,13 @@ This member is an explicit interface member implementation. It can be used only Gets the number of rows changed, inserted, or deleted by execution of the Transact-SQL statement. The number of rows changed, inserted, or deleted; 0 if no rows were affected or the statement failed; and -1 for SELECT statements. - and are the only properties that you can call after the is closed. - + and are the only properties that you can call after the is closed. + ]]> SQL Server Connection Pooling (ADO.NET) @@ -4236,11 +4240,11 @@ This member is an explicit interface member implementation. It can be used only Returns an for the specified column ordinal. The instance for the specified column ordinal. - instance is cast to an interface. - + instance is cast to an interface. + ]]> ADO.NET Overview @@ -4316,11 +4320,11 @@ This member is an explicit interface member implementation. It can be used only Gets the number of fields in the that are not hidden. The number of fields that are not hidden. - are visible. For example, a SELECT on a partial primary key returns the remaining parts of the key as hidden fields. The hidden fields are always appended behind the visible fields. - + are visible. For example, a SELECT on a partial primary key returns the remaining parts of the key as hidden fields. The hidden fields are always appended behind the visible fields. + ]]> DataAdapters and DataReaders (ADO.NET) diff --git a/xml/System.Data/DataReaderExtensions.xml b/xml/System.Data/DataReaderExtensions.xml index fad40ee9d54..493163cead2 100644 --- a/xml/System.Data/DataReaderExtensions.xml +++ b/xml/System.Data/DataReaderExtensions.xml @@ -505,19 +505,19 @@ Gets the value of the specified column as the requested type. The value of the specified column. To be added. - The connection was dropped or closed during data retrieval. + The connection was dropped or closed during data retrieval. -or- - - The data reader was closed during data retrieval. - + + The data reader was closed during data retrieval. + -or- - There is no data ready to be read (for example, the first hasn't been called, or it returned ). + There is no data ready to be read (for example, the first hasn't been called, or it returned ). -or- - The reader tried to read a previously-read column in sequential mode. + The reader tried to read a previously-read column in sequential mode. -or- @@ -567,7 +567,7 @@ - The connection was dropped or closed during data retrieval. - + The connection was dropped or closed during data retrieval. + -or- - The data reader was closed during the data retrieval. + The data reader was closed during the data retrieval. -or- @@ -591,13 +591,14 @@ -or- - Tried to read a previously-read column in sequential mode. + Tried to read a previously-read column in sequential mode. -or- There was an asynchronous operation in progress. This applies to all Get_*_ methods when running in sequential mode, as they could be called while reading a stream. The name specified is not a valid column name. The value returned by the database doesn't match or cannot be cast to . + The cancellation token was canceled. This exception is stored into the returned task. @@ -910,25 +911,25 @@ Gets a stream to retrieve data from the specified column. A stream. - only supports the retrieval of values that can be converted to byte arrays. + only supports the retrieval of values that can be converted to byte arrays. ]]> - The connection was dropped or closed during the data retrieval. - + The connection was dropped or closed during the data retrieval. + -or- - The data reader is closed during the data retrieval. + The data reader is closed during the data retrieval. -or- - There is no data ready to be read (for example, the first hasn't been called, or returned false). + There is no data ready to be read (for example, the first hasn't been called, or returned false). -or- - The data reader tried to read a previously-read column in sequential mode. + The data reader tried to read a previously-read column in sequential mode. -or- @@ -1008,25 +1009,25 @@ Gets a text reader to retrieve data from the column. A text reader. - only supports the retrieval of values that can be converted to character arrays (strings). + only supports the retrieval of values that can be converted to character arrays (strings). ]]> - The connection was dropped or closed during the data retrieval. - + The connection was dropped or closed during the data retrieval. + -or- - The data reader is closed during the data retrieval. + The data reader is closed during the data retrieval. -or- - There is no data ready to be read (for example, the first hasn't been called, or returned false). + There is no data ready to be read (for example, the first hasn't been called, or returned false). -or- - The data reader tried to read a previously-read column in sequential mode. + The data reader tried to read a previously-read column in sequential mode. -or- @@ -1106,11 +1107,11 @@ if the specified column is equivalent to ; otherwise, . - , , and so on) to avoid throwing an exception. - + , , and so on) to avoid throwing an exception. + ]]> The name specified is not a valid column name. @@ -1155,7 +1156,7 @@ ## Remarks This asynchronous method is only needed to avoid blocking the calling thread when the reader is created in sequential mode. - + If sequential mode isn't specified, all column values should become available in memory each time ReadAsync completes, and calling the synchronous version of the method shouldn't block the calling thread. The default implementation of this asynchronous method invokes its synchronous counterpart and returns a completed Task, potentially blocking the calling thread. The default implementation also returns a cancelled task if passed an already cancelled cancellation token. @@ -1163,31 +1164,32 @@ Data providers that support [asynchronous programming](/dotnet/framework/data/adonet/asynchronous-programming) should override the default inmplementation using asynchronous I/O operations. This method accepts a cancellation token that can be used to request the operation to be cancelled early. Implementations may ignore this request. - + Other methods and properties of the DbDataReader object should not be invoked while the returned Task is not yet completed. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - The connection was dropped or closed during the data retrieval. - + The connection was dropped or closed during the data retrieval. + -or- - The data reader is closed during the data retrieval. + The data reader is closed during the data retrieval. -or- - There is no data ready to be read (for example, the first hasn't been called, or returned false). + There is no data ready to be read (for example, the first hasn't been called, or returned false). -or- - Trying to read a previously read column in sequential mode. + Trying to read a previously read column in sequential mode. -or- - + There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream. The name specified is not a valid column name. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Diagnostics/Process.xml b/xml/System.Diagnostics/Process.xml index ec21fa9bc0e..9e993943bf2 100644 --- a/xml/System.Diagnostics/Process.xml +++ b/xml/System.Diagnostics/Process.xml @@ -6851,6 +6851,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Formats.Tar/TarEntry.xml b/xml/System.Formats.Tar/TarEntry.xml index c48a990e6bc..ac83793630d 100644 --- a/xml/System.Formats.Tar/TarEntry.xml +++ b/xml/System.Formats.Tar/TarEntry.xml @@ -190,6 +190,7 @@ A directory exists with the same name as An I/O problem occurred. The entry type is unsupported. Permissions are insufficient. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Formats.Tar/TarFile.xml b/xml/System.Formats.Tar/TarFile.xml index 25ab7b88f8c..3dafa70d3dc 100644 --- a/xml/System.Formats.Tar/TarFile.xml +++ b/xml/System.Formats.Tar/TarFile.xml @@ -131,6 +131,7 @@ does not support writing. The directory path is not found. An I/O exception occurred. + The cancellation token was canceled. This exception is stored into the returned task. @@ -168,6 +169,7 @@ or is empty. The directory path is not found. An I/O exception occurred. + The cancellation token was canceled. This exception is stored into the returned task. @@ -309,6 +311,7 @@ Extracting one of the tar entries would have resulted in a file outside the spec does not support reading. An I/O exception occurred. + The cancellation token was canceled. This exception is stored into the returned task. @@ -356,6 +359,7 @@ Extracting one of the tar entries would have resulted in a file outside the spec or is empty. An I/O exception occurred. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Formats.Tar/TarReader.xml b/xml/System.Formats.Tar/TarReader.xml index 924a3369056..7da07f4063d 100644 --- a/xml/System.Formats.Tar/TarReader.xml +++ b/xml/System.Formats.Tar/TarReader.xml @@ -191,6 +191,7 @@ More than one Global Extended Attributes Entry was found in the current archive. An I/O problem occurred. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Formats.Tar/TarWriter.xml b/xml/System.Formats.Tar/TarWriter.xml index 5cda9867e26..6c69b07c1a3 100644 --- a/xml/System.Formats.Tar/TarWriter.xml +++ b/xml/System.Formats.Tar/TarWriter.xml @@ -322,6 +322,7 @@ This method stores in the task it returns all non-usage exceptions that the meth is . An I/O problem occurred. + The cancellation token was canceled. This exception is stored into the returned task. @@ -354,6 +355,7 @@ This method stores in the task it returns all non-usage exceptions that the meth or is or empty. An I/O problem occurred. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO.Compression/BrotliStream.xml b/xml/System.IO.Compression/BrotliStream.xml index 8e24f99ddf2..89ee5131184 100644 --- a/xml/System.IO.Compression/BrotliStream.xml +++ b/xml/System.IO.Compression/BrotliStream.xml @@ -577,6 +577,7 @@ Asynchronously clears all buffers for this Brotli stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. A task that represents the asynchronous flush operation. If the operation is canceled before it completes, the returned task contains the value for the property.This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -757,6 +758,7 @@ Use the property to determine whether the current instance supports reading. If the operation is canceled before it completes, the returned task contains the value for the property. + The cancellation token was canceled. This exception is stored into the returned task. @@ -801,6 +803,7 @@ If the operation is canceled before it completes, the returned task contains the value for the property. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1010,6 +1013,7 @@ Use the property to determine whether the current instance supports writing. If the operation is canceled before it completes, the returned task contains the value for the property. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1054,6 +1058,7 @@ If the operation is canceled before it completes, the returned task contains the value for the property. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO.Compression/DeflateStream.xml b/xml/System.IO.Compression/DeflateStream.xml index 00ee6dcccba..1ea7fff14f4 100644 --- a/xml/System.IO.Compression/DeflateStream.xml +++ b/xml/System.IO.Compression/DeflateStream.xml @@ -60,12 +60,12 @@ Initializes a new instance of the class. - class to compress a file larger than 4 GB will cause an exception. - + Using the class to compress a file larger than 4 GB will cause an exception. + ]]> @@ -112,7 +112,7 @@ ## Remarks - You use this constructor when you want to specify whether compression efficiency or speed is more important for an instance of the class. + You use this constructor when you want to specify whether compression efficiency or speed is more important for an instance of the class. [!INCLUDE[remarks](~/includes/remarks/System.IO.Compression/DeflateStream/.ctor_Stream_CompressionLevel.md)] @@ -177,14 +177,14 @@ is . - is not a valid value. - - -or- - - is and is . - - -or- - + is not a valid value. + + -or- + + is and is . + + -or- + is and is . @@ -295,14 +295,14 @@ You use this constructor when you want to specify whether compression efficiency is . - is not a valid value. - - -or- - - is and is . - - -or- - + is not a valid value. + + -or- + + is and is . + + -or- + is and is . @@ -416,7 +416,7 @@ You use this constructor when you want to specify whether compression efficiency Begins an asynchronous read operation. (Consider using the method instead.) An object that represents the asynchronous read operation, which could still be pending. - + The cancellation token was canceled. This exception is stored into the returned task. @@ -766,20 +767,20 @@ This method stores in the task it returns all non-usage exceptions that the meth to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. - + method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). @@ -875,16 +876,16 @@ Calling `DisposeAsync` allows the resources used by the Waits for the pending asynchronous read to complete. (Consider using the method instead.) The number of bytes read from the stream, between 0 (zero) and the number of bytes you requested. returns 0 only at the end of the stream; otherwise, it blocks until at least one byte is available. - method. The method is still available in the .NET Framework 4.5 to support legacy code; however, you can implement asynchronous I/O operations more easily by using the new async methods. For more information, see [Asynchronous File I/O](/dotnet/standard/io/asynchronous-file-i-o). - - Call this method to determine how many bytes were read from the stream. This method can be called once to return the amount of bytes read between calls to and . - - This method blocks until the I/O operation has completed. - + + Call this method to determine how many bytes were read from the stream. This method can be called once to return the amount of bytes read between calls to and . + + This method blocks until the I/O operation has completed. + ]]> @@ -944,16 +945,16 @@ The stream is . A reference to the outstanding asynchronous I/O request. Ends an asynchronous write operation. (Consider using the method instead.) - method. The method is still available in the .NET Framework 4.5 to support legacy code; however, you can implement asynchronous I/O operations more easily by using the new async methods. For more information, see [Asynchronous File I/O](/dotnet/standard/io/asynchronous-file-i-o). - - must be called only once for every call to the method. - - This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to . Exceptions thrown by the thread pool thread will not be visible when calling . - + + must be called only once for every call to the method. + + This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to . Exceptions thrown by the thread pool thread will not be visible when calling . + ]]> @@ -1005,12 +1006,12 @@ The end write call is invalid. The current implementation of this method has no functionality. - . - + ]]> The stream is closed. @@ -1060,6 +1061,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1242,28 +1244,28 @@ This method read a maximum of `buffer.Length` bytes from the current stream and Reads a number of decompressed bytes into the specified byte array. The number of bytes that were read into the byte array. - and methods. - + and methods. + :::code language="csharp" source="~/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/Deflate/MemoryWriteReadExample.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/Deflate/MemoryWriteReadExample.vb" id="Snippet1"::: + ]]> is . - The value was when the object was created. - + The value was when the object was created. + -or- - + The underlying stream does not support reading. - or is less than zero. - - -or- - + or is less than zero. + + -or- + length minus the index starting point is less than . The data is in an invalid format. The stream is closed. @@ -1316,6 +1318,7 @@ If the operation is canceled before it completes, the returned task contains the ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1368,7 +1371,7 @@ If the operation is canceled before it completes, the returned task contains the A task that represents the asynchronous read operation, which wraps the total number of bytes read into the . The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the Deflate stream has been reached. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1609,14 +1613,14 @@ If the write operation is successful, the position within the Deflate stream adv The maximum number of bytes to write. Writes compressed bytes to the underlying stream from the specified byte array. - and methods. - + and methods. + :::code language="csharp" source="~/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/Deflate/MemoryWriteReadExample.vb" id="Snippet1"::: - + ]]> @@ -1668,6 +1672,7 @@ If the operation is canceled before it completes, the returned task contains the ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1733,6 +1738,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO.Compression/GZipStream.xml b/xml/System.IO.Compression/GZipStream.xml index db739b4bb3b..bb8e11831d5 100644 --- a/xml/System.IO.Compression/GZipStream.xml +++ b/xml/System.IO.Compression/GZipStream.xml @@ -103,21 +103,21 @@ One of the enumeration values that indicates whether to emphasize speed or compression efficiency when compressing data to the stream. Initializes a new instance of the class by using the specified stream and compression level. - class. - - This constructor overload uses the compression mode . To set the compression mode to another value, use the or overload. + You use this constructor when you want to specify whether compression efficiency or speed is more important for an instance of the class. + + This constructor overload uses the compression mode . To set the compression mode to another value, use the or overload. ## Examples The following example shows how to set the compression mode when creating a object. - + :::code language="csharp" source="~/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/FileCompressionModeExample.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/FileCompressionModeExample.vb" id="Snippet1"::: + ]]> @@ -170,35 +170,35 @@ One of the enumeration values that indicates whether to compress data to the stream or decompress data from the stream. Initializes a new instance of the class by using the specified stream and compression mode. - owns the underlying stream, so closing the `stream` parameter also closes the underlying stream. Note that the state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created. - - If an instance of the class is created with the `mode` parameter equal to `Compress` and no further action occurs, the stream will appear as a valid, empty compressed file. - - By default, the compression level is set to when the compression mode is . + owns the underlying stream, so closing the `stream` parameter also closes the underlying stream. Note that the state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created. + + If an instance of the class is created with the `mode` parameter equal to `Compress` and no further action occurs, the stream will appear as a valid, empty compressed file. + + By default, the compression level is set to when the compression mode is . ## Examples The following example shows how to set the compression mode when creating a object. - + :::code language="csharp" source="~/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/FileCompressionModeExample.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/FileCompressionModeExample.vb" id="Snippet1"::: + ]]> is . - is not a valid enumeration value. - - -or- - - is and is . - - -or- - + is not a valid enumeration value. + + -or- + + is and is . + + -or- + is and is . @@ -243,12 +243,12 @@ The following example shows how to set the compression mode when creating a to leave the stream object open after disposing the object; otherwise, . Initializes a new instance of the class by using the specified stream and compression level, and optionally leaves the stream open. - class, and whether to leave the stream object open after disposing the object. - - This constructor overload uses the compression mode . To set the compression mode to another value, use the or overload. + class, and whether to leave the stream object open after disposing the object. + + This constructor overload uses the compression mode . To set the compression mode to another value, use the or overload. ## Examples @@ -256,7 +256,7 @@ The following example shows how to set the compression level when creating a @@ -306,28 +306,28 @@ The following example shows how to set the compression level when creating a to leave the stream open after disposing the object; otherwise, . Initializes a new instance of the class by using the specified stream and compression mode, and optionally leaves the stream open. - owns the underlying stream, so closing the `stream` parameter also closes the underlying stream. Note that the state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created. - - If an instance of the class is created with the `mode` parameter equal to `Compress` and no further action occurs, the stream will appear as a valid, empty compressed file. - - By default, the compression level is set to when the compression mode is . - + owns the underlying stream, so closing the `stream` parameter also closes the underlying stream. Note that the state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created. + + If an instance of the class is created with the `mode` parameter equal to `Compress` and no further action occurs, the stream will appear as a valid, empty compressed file. + + By default, the compression level is set to when the compression mode is . + ]]> is . - is not a valid value. - - -or- - - is and is . - - -or- - + is not a valid value. + + -or- + + is and is . + + -or- + is and is . @@ -435,7 +435,7 @@ The following example shows how to set the compression level when creating a Begins an asynchronous read operation. (Consider using the method instead.) An object that represents the asynchronous read operation, which could still be pending. - Begins an asynchronous write operation. (Consider using the method instead.) An object that represents the asynchronous write operation, which could still be pending. - method. The method is still available in .NET Framework 4.5 to support legacy code; however, you can implement asynchronous I/O operations more easily by using the new async methods. For more information, see [Asynchronous File I/O](/dotnet/standard/io/asynchronous-file-i-o). - - The method starts an asynchronous write operation to a stream object. - - You must create a callback method that implements the delegate and pass its name to the method. - + + The method starts an asynchronous write operation to a stream object. + + You must create a callback method that implements the delegate and pass its name to the method. + ]]> - The underlying stream is . - - -or- - + The underlying stream is . + + -or- + The underlying stream is closed. @@ -756,6 +756,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -799,19 +800,19 @@ This method stores in the task it returns all non-usage exceptions that the meth to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. - + method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). @@ -907,14 +908,14 @@ Calling `DisposeAsync` allows the resources used by the Waits for the pending asynchronous read to complete. (Consider using the method instead.) The number of bytes read from the stream, between 0 (zero) and the number of bytes you requested. returns 0 only at the end of the stream; otherwise, it blocks until at least one byte is available. - method. The method is still available in .NET Framework 4.5 to support legacy code; however, you can implement asynchronous I/O operations more easily by using the new async methods. For more information, see [Asynchronous File I/O](/dotnet/standard/io/asynchronous-file-i-o). - - Call this method to determine how many bytes were read from the stream. This method can be called once to return the amount of bytes read between calls to and . - - This method blocks until the I/O operation has completed. + + Call this method to determine how many bytes were read from the stream. This method can be called once to return the amount of bytes read between calls to and . + + This method blocks until the I/O operation has completed. ]]> @@ -970,19 +971,19 @@ Calling `DisposeAsync` allows the resources used by the The object that represents the asynchronous call. Handles the end of an asynchronous write operation. (Consider using the method instead.) - method. The method is still available in .NET Framework 4.5 to support legacy code; however, you can implement asynchronous I/O operations more easily by using the new async methods. For more information, see [Asynchronous File I/O](/dotnet/standard/io/asynchronous-file-i-o). - - The method completes the asynchronous write operation started in the method. - + + The method completes the asynchronous write operation started in the method. + ]]> - The underlying stream is . - - -or- - + The underlying stream is . + + -or- + The underlying stream is closed. @@ -1078,6 +1079,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1260,8 +1262,8 @@ This method read a maximum of `buffer.Length` bytes from the current stream and Reads a number of decompressed bytes into the specified byte array. The number of bytes that were decompressed into the byte array. If the end of the stream has been reached, zero or the number of bytes read is returned. - is thrown as one of the last operations. A cyclic redundancy check (CRC) is performed as one of the last operations of this method. @@ -1272,21 +1274,21 @@ The following example shows how to compress and decompress bytes by using the is . - The value was when the object was created. - + The value was when the object was created. + -or- - + The underlying stream does not support reading. - or is less than zero. - - -or- - + or is less than zero. + + -or- + length minus the index starting point is less than . The data is in an invalid format. The stream is closed. @@ -1339,6 +1341,7 @@ If the operation is canceled before it completes, the returned task contains the ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1391,7 +1394,7 @@ If the operation is canceled before it completes, the returned task contains the A task that represents the asynchronous read operation, which wraps the total number of bytes read into the . The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the GZip stream has been reached. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1632,18 +1636,18 @@ If the write operation is successful, the position within the GZip stream advanc The maximum number of bytes to write. Writes compressed bytes to the underlying GZip stream from the specified byte array. - or method is called. +The write operation might not occur immediately but is buffered until the buffer size is reached or until the or method is called. ## Examples The following example shows how to compress and decompress bytes by using the and methods. :::code language="csharp" source="~/snippets/csharp/System.IO.Compression/GZip/MemoryWriteReadExample.cs" id="Snippet1"::: -:::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/MemoryWriteReadExample.vb" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/MemoryWriteReadExample.vb" id="Snippet1"::: ]]> @@ -1697,6 +1701,7 @@ If the operation is canceled before it completes, the returned task contains the ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1762,6 +1767,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO.Compression/ZLibStream.xml b/xml/System.IO.Compression/ZLibStream.xml index d0a12a68cf4..60bcc577732 100644 --- a/xml/System.IO.Compression/ZLibStream.xml +++ b/xml/System.IO.Compression/ZLibStream.xml @@ -372,6 +372,7 @@ The stream does not support reading or writing. The stream is closed. Only one asynchronous reader or writer is allowed at a time. + The cancellation token was canceled. This exception is stored into the returned task. @@ -519,6 +520,7 @@ Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. A task that represents the asynchronous flush operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -646,6 +648,7 @@ Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous completion of the operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -678,6 +681,7 @@ Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous completion of the operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -835,6 +839,7 @@ Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous completion of the operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -867,6 +872,7 @@ Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous completion of the operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO.Hashing/NonCryptographicHashAlgorithm.xml b/xml/System.IO.Hashing/NonCryptographicHashAlgorithm.xml index 6d519e9bf73..d4bbd10799f 100644 --- a/xml/System.IO.Hashing/NonCryptographicHashAlgorithm.xml +++ b/xml/System.IO.Hashing/NonCryptographicHashAlgorithm.xml @@ -150,6 +150,7 @@ This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -233,7 +234,7 @@ Implementations of this method must write exactly bytes to `destination`. Do not assume that the buffer was zero-initialized. - + The class validates the @@ -325,13 +326,13 @@ The class validates the Implementations of this method must write exactly bytes to `destination`. Do not assume that the buffer was zero-initialized. - + The class validates the size of the buffer before calling this method, and slices the span down to be exactly in length. - + The default implementation of this method calls diff --git a/xml/System.IO.IsolatedStorage/IsolatedStorageFileStream.xml b/xml/System.IO.IsolatedStorage/IsolatedStorageFileStream.xml index f9e2a06ac12..c64c5d4fa28 100644 --- a/xml/System.IO.IsolatedStorage/IsolatedStorageFileStream.xml +++ b/xml/System.IO.IsolatedStorage/IsolatedStorageFileStream.xml @@ -51,27 +51,27 @@ Exposes a file within isolated storage. - , you can use an instance of in most situations where a might otherwise be used, such as to construct a or . - - This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - + , you can use an instance of in most situations where a might otherwise be used, such as to construct a or . + + This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. + > [!IMPORTANT] -> Isolated storage is not available for Windows 8.x Store apps. Instead, use the application data classes in the `Windows.Storage` namespaces included in the Windows Runtime API to store local data and files. For more information, see [Application data](https://go.microsoft.com/fwlink/?LinkId=229175) in the Windows Dev Center. - - - -## Examples - The following console application demonstrates how you can use and to write data to an Isolated Storage file. The user is requested to log in. If the user is a new user, a News URL and a Sports URL are recorded as personal preferences in Isolated Storage. If the user is a returning user, the user's current preferences are displayed. The code examples used throughout this namespace are presented in the context of this sample application. You can use the [Storeadm.exe (Isolated Storage Tool)](/dotnet/framework/tools/storeadm-exe-isolated-storage-tool) utility to list and remove the Isolated Storage files that are created with this console application. - +> Isolated storage is not available for Windows 8.x Store apps. Instead, use the application data classes in the `Windows.Storage` namespaces included in the Windows Runtime API to store local data and files. For more information, see [Application data](https://go.microsoft.com/fwlink/?LinkId=229175) in the Windows Dev Center. + + + +## Examples + The following console application demonstrates how you can use and to write data to an Isolated Storage file. The user is requested to log in. If the user is a new user, a News URL and a Sports URL are recorded as personal preferences in Isolated Storage. If the user is a returning user, the user's current preferences are displayed. The code examples used throughout this namespace are presented in the context of this sample application. You can use the [Storeadm.exe (Isolated Storage Tool)](/dotnet/framework/tools/storeadm-exe-isolated-storage-tool) utility to list and remove the Isolated Storage files that are created with this console application. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet1"::: + ]]> @@ -124,16 +124,16 @@ One of the values. Initializes a new instance of an object giving access to the file designated by in the specified . - object. To specify a different isolated storage scope, or to allow the store to remain open (so multiple objects can be opened from it), use the form of the constructor that accepts an object. - - The `mode` parameter indicates whether a new file should be created, an existing one used, and so on. - + object. To specify a different isolated storage scope, or to allow the store to remain open (so multiple objects can be opened from it), use the form of the constructor that accepts an object. + + The `mode` parameter indicates whether a new file should be created, an existing one used, and so on. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and can cause an exception to be thrown. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and can cause an exception to be thrown. + ]]> The is badly formed. @@ -182,16 +182,16 @@ A bitwise combination of the values. Initializes a new instance of the class giving access to the file designated by , in the specified , with the kind of requested. - object. To specify a different isolated storage scope, or to allow the store to remain open (so multiple objects can be opened from it), use the form of the constructor that accepts an object. - - The `mode` parameter indicates whether a new file should be created or an existing one used. The `access` parameter includes read-only, read/write, and write-only. - + object. To specify a different isolated storage scope, or to allow the store to remain open (so multiple objects can be opened from it), use the form of the constructor that accepts an object. + + The `mode` parameter indicates whether a new file should be created or an existing one used. The `access` parameter includes read-only, read/write, and write-only. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. + ]]> The is badly formed. @@ -241,23 +241,23 @@ The in which to open the . Initializes a new instance of the class giving access to the file designated by , in the specified , and in the context of the specified by . - [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. - - - -## Examples - The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. + + + +## Examples + The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet11"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet11"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet11"::: + ]]> The is badly formed. @@ -309,23 +309,23 @@ A bitwise combination of the values. Initializes a new instance of the class giving access to the file designated by , in the specified , with the specified file , using the file sharing mode specified by . - object. To specify a different isolated storage scope, or to allow the store to remain open (so multiple objects can be opened from it), use the form of the constructor that accepts an object. - + object. To specify a different isolated storage scope, or to allow the store to remain open (so multiple objects can be opened from it), use the form of the constructor that accepts an object. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and can cause an exception to be thrown. - - - -## Examples - The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and can cause an exception to be thrown. + + + +## Examples + The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet15"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet15"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet15"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet15"::: + ]]> The is badly formed. @@ -377,23 +377,23 @@ The in which to open the . Initializes a new instance of the class giving access to the file designated by in the specified , with the specified file , and in the context of the specified by . - [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. - - - -## Examples - The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. + + + +## Examples + The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet10"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet10"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet10"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet10"::: + ]]> The is badly formed. @@ -448,16 +448,16 @@ The buffer size. Initializes a new instance of the class giving access to the file designated by , in the specified , with the specified file , using the file sharing mode specified by , with the specified. - object. To specify a different isolated storage scope, or to allow the store to remain open (so multiple objects can be opened from it), use the form of the constructor that accepts an object. - - The `mode` parameter indicates whether a new file should be created or an existing one used. The `access` parameter includes read-only, read/write, and write-only. - + object. To specify a different isolated storage scope, or to allow the store to remain open (so multiple objects can be opened from it), use the form of the constructor that accepts an object. + + The `mode` parameter indicates whether a new file should be created or an existing one used. The `access` parameter includes read-only, read/write, and write-only. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. + ]]> The is badly formed. @@ -511,23 +511,23 @@ The in which to open the . Initializes a new instance of the class giving access to the file designated by , in the specified , with the specified file , using the file sharing mode specified by , and in the context of the specified by . - [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. - - - -## Examples - The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. + + + +## Examples + The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet11"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet11"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet11"::: + ]]> The is badly formed. @@ -590,23 +590,23 @@ The in which to open the . Initializes a new instance of the class giving access to the file designated by , in the specified , with the specified file , using the file sharing mode specified by , with the specified, and in the context of the specified by . - [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. - - - -## Examples - The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and can cause an exception to be thrown. + + + +## Examples + The following code example demonstrates the use of this constructor. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet12"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet12"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet12"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet12"::: + ]]> The is badly formed. @@ -671,13 +671,13 @@ Begins an asynchronous read. An object that represents the asynchronous read, which is possibly still pending. This must be passed to this stream's method to determine how many bytes were read. This can be done either by the same code that called or in a callback passed to . - with this to find out how many bytes were read. - + with this to find out how many bytes were read. + ]]> An asynchronous read was attempted past the end of the file. @@ -744,15 +744,15 @@ Begins an asynchronous write. An that represents the asynchronous write, which is possibly still pending. This must be passed to this stream's method to ensure that the write is complete, then frees resources appropriately. This can be done either by the same code that called or in a callback passed to . - object is writable, writing at the end of the stream expands the stream. - - The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. - - You must call with the object that this method returns to find out how many bytes were written. - + object is writable, writing at the end of the stream expands the stream. + + The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. + + You must call with the object that this method returns to find out how many bytes were written. + ]]> An asynchronous write was attempted past the end of the file. @@ -796,20 +796,20 @@ if an object can be read; otherwise, . - object can be read. - - - -## Examples - The following code example demonstrates how you could use the property, as a check to see whether a stream can be read before calling the or methods. For the complete context of this example, see the overview. - + object can be read. + + + +## Examples + The following code example demonstrates how you could use the property, as a check to see whether a stream can be read before calling the or methods. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet11"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet11"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet11"::: + ]]> @@ -852,11 +852,11 @@ if an object supports seek operations; otherwise, . - object supports seek operations. - + object supports seek operations. + ]]> @@ -899,20 +899,20 @@ if an object can be written; otherwise, . - object can be written. - - - -## Examples - The following code example demonstrates how you could use the property, as a check to see whether a stream can be read before calling the or methods. For the complete context of this example, see the overview. - + object can be written. + + + +## Examples + The following code example demonstrates how you could use the property, as a check to see whether a stream can be read before calling the or methods. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet13"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet13"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet13"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet13"::: + ]]> @@ -1041,19 +1041,19 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to true. `Finalize` invokes with `disposing` set to false. - - When the `disposing` parameter is true, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. - + method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to true. `Finalize` invokes with `disposing` set to false. + + When the `disposing` parameter is true, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). @@ -1131,11 +1131,11 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) Ends a pending asynchronous read request. The number of bytes read from the stream, between zero and the number of requested bytes. Streams will only return zero at the end of the stream. Otherwise, they will block until at least one byte is available. - must be called exactly once on every object from , and calling is the only way to know how many bytes were read from the . will block until the I/O operation has completed. - + must be called exactly once on every object from , and calling is the only way to know how many bytes were read from the . will block until the I/O operation has completed. + ]]> The is . @@ -1180,13 +1180,13 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) The pending asynchronous I/O request to end. Ends an asynchronous write. - must be called exactly once on every from . - - will block until the I/O operation has completed. - + must be called exactly once on every from . + + will block until the I/O operation has completed. + ]]> The parameter is . @@ -1239,13 +1239,13 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) Clears buffers for this stream and causes any buffered data to be written to the file. - performs two functions. First, any data previously written to the buffer is copied to the file and the buffer is cleared. Second, if is `true` and data was previously copied from the file to the buffer for reading, the current position within the file is decremented by the number of unread bytes in the buffer. The buffer is then cleared. - - Use the method overload when you want to ensure that all buffered data in intermediate file buffers is written to disk. - + performs two functions. First, any data previously written to the buffer is copied to the file and the buffer is cleared. Second, if is `true` and data was previously copied from the file to the buffer for reading, the current position within the file is decremented by the number of unread bytes in the buffer. The buffer is then cleared. + + Use the method overload when you want to ensure that all buffered data in intermediate file buffers is written to disk. + ]]> @@ -1289,11 +1289,11 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) to flush all intermediate file buffers; otherwise, . Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers. - @@ -1331,6 +1331,7 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) Asynchronously clears buffers for this stream and causes any buffered data to be written to the file. A task that represents the asynchronous flush operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1391,20 +1392,20 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) Gets the file handle for the file that the current object encapsulates. Accessing this property is not permitted on an object, and throws an . The file handle for the file that the current object encapsulates. - . - - - -## Examples - The following code example demonstrates the property. - + . + + + +## Examples + The following code example demonstrates the property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet4"::: + ]]> The property always generates this exception. @@ -1447,20 +1448,20 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) if the object supports asynchronous access; otherwise, . - objects cannot be created, unlike . However, the , , , and methods are supported on synchronous instances, with some performance penalties. - - - -## Examples - The following code example demonstrates how you can use the property to verify that an is synchronous. For the complete context of this example, see the overview. - + objects cannot be created, unlike . However, the , , , and methods are supported on synchronous instances, with some performance penalties. + + + +## Examples + The following code example demonstrates how you can use the property to verify that an is synchronous. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet7"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet7"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet7"::: + ]]> @@ -1503,20 +1504,20 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) Gets the length of the object. The length of the object in bytes. - represents the number of bytes currently in the file. It is not affected by isolated storage quota. - - - -## Examples - The following code example demonstrates the property. - + represents the number of bytes currently in the file. It is not affected by isolated storage quota. + + + +## Examples + The following code example demonstrates the property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet14"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet14"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet14"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet14"::: + ]]> @@ -1565,11 +1566,11 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) The number of bytes to lock. Prevents other processes from reading from or writing to the stream. - @@ -1615,20 +1616,20 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) Gets or sets the current position of the current object. The current position of this object. - property is `true`. - - - -## Examples - The following code example uses the property to write data to a file. - + property is `true`. + + + +## Examples + The following code example uses the property to write data to a file. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet14"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet14"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet14"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet14"::: + ]]> The position cannot be set to a negative number. @@ -1715,11 +1716,11 @@ Dim source As New IsolatedStorageFileStream(UserName,FileMode.Open,isoFile) Copies bytes from the current buffered object to a byte array. The total number of bytes read into the . This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream is reached. - class, or an array of one of the following types: , , , , , , , , , , or . +The `buffer` parameter can be an instance of the class, or an array of one of the following types: , , , , , , , , , , or . If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged. @@ -1766,6 +1767,7 @@ The method wi Asynchronously copies bytes from the current buffered object to a byte memory range. A task that represents the asynchronous read operation. It wraps the total number of bytes read into the . This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream is reached. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1806,11 +1808,11 @@ The method wi Asynchronously copies bytes from the current buffered object to a byte array. A task that represents the asynchronous read operation. It wraps the total number of bytes read into the . This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream is reached. - class, or an array of one of the following types: , , , , , , , , , , or . +The `buffer` parameter can be an instance of the class, or an array of one of the following types: , , , , , , , , , , or . If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged. @@ -1822,6 +1824,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1862,15 +1865,15 @@ This method stores in the task it returns all non-usage exceptions that the meth Reads a single byte from the object in isolated storage. The 8-bit unsigned integer value read from the isolated storage file. - method can be used to read data from an object. For the complete context of this example, see the overview. - + method can be used to read data from an object. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet14"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet14"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet14"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet14"::: + ]]> @@ -1916,11 +1919,11 @@ This method stores in the task it returns all non-usage exceptions that the meth Gets a object that represents the operating system file handle for the file that the current object encapsulates. A object that represents the operating system file handle for the file that the current object encapsulates. - property is not supported and always generates an exception. - + property is not supported and always generates an exception. + ]]> The property always generates this exception. @@ -1975,11 +1978,11 @@ This method stores in the task it returns all non-usage exceptions that the meth Sets the current position of this object to the specified value. The new position in the object. - objects support positioning beyond the length of the stream, others will throw an exception in this case. - + objects support positioning beyond the length of the stream, others will throw an exception in this case. + ]]> The must be one of the values. @@ -2031,11 +2034,11 @@ This method stores in the task it returns all non-usage exceptions that the meth The new length of the object. Sets the length of this object to the specified . - object, the stream is truncated. If the specified `value` is larger than the current length of the stream, the stream is expanded. If the stream is expanded, the contents of the stream between the old and the new length are undefined. In order to use this method, an object must support both writing and seeking. - + object, the stream is truncated. If the specified `value` is larger than the current length of the stream, the stream is expanded. If the stream is expanded, the contents of the stream between the old and the new length are undefined. In order to use this method, an object must support both writing and seeking. + ]]> @@ -2175,11 +2178,11 @@ This method stores in the task it returns all non-usage exceptions that the meth The maximum number of bytes to write. Writes a block of bytes to the isolated storage file stream object using data read from a buffer consisting of a byte array. - object is advanced by the number of bytes written. If an exception occurs, the current position of the object is unchanged. +If the write operation is successful, the current position of the object is advanced by the number of bytes written. If an exception occurs, the current position of the object is unchanged. ]]> @@ -2221,6 +2224,7 @@ If the write operation is successful, the current position of the Asynchronously writes a block of bytes to the isolated storage file stream object using data read from a buffer consisting of a read-only byte memory range. A task that represents the asynchronous write operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2261,16 +2265,17 @@ If the write operation is successful, the current position of the Asynchronously writes a block of bytes to the isolated storage file stream object using data read from a buffer consisting of a byte array. A task that represents the asynchronous write operation. - object is advanced by the number of bytes written. If an exception occurs, the current position of the object is unchanged. +If the write operation is successful, the current position of the object is advanced by the number of bytes written. If an exception occurs, the current position of the object is unchanged. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -2319,15 +2324,15 @@ This method stores in the task it returns all non-usage exceptions that the meth The byte value to write to the isolated storage file. Writes a single byte to the object. - method can be used to read data from an object. For the complete context of this example, see the overview. - + method can be used to read data from an object. For the complete context of this example, see the overview. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/CPP/source.cpp" id="Snippet14"::: :::code language="csharp" source="~/snippets/csharp/System.IO.IsolatedStorage/IsolatedStorageFile/Close/source.cs" id="Snippet14"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet14"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.IsolatedStorage.IsolatedStorage/VB/source.vb" id="Snippet14"::: + ]]> The write attempt exceeds the quota for the object. diff --git a/xml/System.IO.Pipelines/PipeReader.xml b/xml/System.IO.Pipelines/PipeReader.xml index 609b0a48f12..5020f56421d 100644 --- a/xml/System.IO.Pipelines/PipeReader.xml +++ b/xml/System.IO.Pipelines/PipeReader.xml @@ -309,6 +309,7 @@ The canceled Asynchronously reads the bytes from the and writes them to the specified , using a specified buffer size and cancellation token. A task that represents the asynchronous copy operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -339,6 +340,7 @@ The canceled Asynchronously reads the bytes from the and writes them to the specified stream, using a specified cancellation token. A task that represents the asynchronous copy operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -482,6 +484,7 @@ The canceled Asynchronously reads a sequence of bytes from the current . A representing the asynchronous read operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -517,6 +520,7 @@ The call returns if the has read the `mini ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -553,6 +557,7 @@ The call returns if the has read the `mini ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO.Pipelines/PipeWriter.xml b/xml/System.IO.Pipelines/PipeWriter.xml index 92e2a979095..eff343ed884 100644 --- a/xml/System.IO.Pipelines/PipeWriter.xml +++ b/xml/System.IO.Pipelines/PipeWriter.xml @@ -257,6 +257,7 @@ The canceled Asynchronously reads the bytes from the specified stream and writes them to the . A task that represents the asynchronous copy operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -318,6 +319,7 @@ The canceled Makes bytes written available to and runs continuation. A task that represents and wraps the asynchronous flush operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -517,6 +519,7 @@ You must request a new buffer after calling Writes the specified byte memory range to the pipe and makes data accessible to the . A task that represents the asynchronous write operation, and wraps the flush asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO.Pipelines/StreamPipeExtensions.xml b/xml/System.IO.Pipelines/StreamPipeExtensions.xml index 9ea93da4ba6..37c6f364b27 100644 --- a/xml/System.IO.Pipelines/StreamPipeExtensions.xml +++ b/xml/System.IO.Pipelines/StreamPipeExtensions.xml @@ -52,6 +52,7 @@ Asynchronously reads the bytes from the and writes them to the specified , using a cancellation token. A task that represents the asynchronous copy operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO.Pipes/NamedPipeClientStream.xml b/xml/System.IO.Pipes/NamedPipeClientStream.xml index f8a68e8b97c..3396b6b6996 100644 --- a/xml/System.IO.Pipes/NamedPipeClientStream.xml +++ b/xml/System.IO.Pipes/NamedPipeClientStream.xml @@ -38,21 +38,21 @@ Exposes a around a named pipe, which supports both synchronous and asynchronous read and write operations. - objects. - - Any process can act as either a named pipe server or client, or both. - -## Examples - The following example demonstrates a way to send a string from a parent process to a child process on the same computer using named pipes. This example creates a object in a parent process. The object has a value of . The server then waits for a object in a child process to connect to it. In this example, both processes are on the same computer and the object has a value of . The parent process then sends a user-supplied string to the child process. The string is displayed to the console. - - This example is for the client process, which connects to the server process. For the entire code sample, including the code for both the pipe client and server, see [How to: Use Named Pipes for Network Interprocess Communication](/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication). - + objects. + + Any process can act as either a named pipe server or client, or both. + +## Examples + The following example demonstrates a way to send a string from a parent process to a child process on the same computer using named pipes. This example creates a object in a parent process. The object has a value of . The server then waits for a object in a child process to connect to it. In this example, both processes are on the same computer and the object has a value of . The parent process then sends a user-supplied string to the child process. The string is displayed to the console. + + This example is for the client process, which connects to the server process. For the entire code sample, including the code for both the pipe client and server, see [How to: Use Named Pipes for Network Interprocess Communication](/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication). + :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/NamedPipeClientStream/Overview/Program.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeClientStream_Sample1/vb/program.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeClientStream_Sample1/vb/program.vb" id="Snippet01"::: + ]]> @@ -113,21 +113,21 @@ The name of the pipe. Initializes a new instance of the class with the specified pipe name. - value of . - -- A default value of . - -- A default value of . - -- A default value of . - + value of . + +- A default value of . + +- A default value of . + +- A default value of . + ]]> @@ -186,19 +186,19 @@ The name of the pipe. Initializes a new instance of the class with the specified pipe and server names. - value of . - -- A default value of . - -- A default value of . - -- A default value of . - + value of . + +- A default value of . + +- A default value of . + +- A default value of . + ]]> @@ -259,25 +259,25 @@ One of the enumeration values that determines the direction of the pipe. Initializes a new instance of the class with the specified pipe and server names, and the specified pipe direction. - value of . - -- A default value of . - -- A default value of . - - - -## Examples - The following example demonstrates a method to send a string from a parent process to a child process using named pipes. This example creates a object in a child process, which then connects to a pipe on the local computer. The server example can be seen in the class. This example is part of a larger example provided for the and classes. - + value of . + +- A default value of . + +- A default value of . + + + +## Examples + The following example demonstrates a method to send a string from a parent process to a child process using named pipes. This example creates a object in a child process, which then connects to a pipe on the local computer. The server example can be seen in the class. This example is part of a larger example provided for the and classes. + :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/NamedPipeClientStream/Overview/Program.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeClientStream_Sample1/vb/program.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeClientStream_Sample1/vb/program.vb" id="Snippet01"::: + ]]> @@ -285,10 +285,10 @@ or is a zero-length string. - is set to "anonymous". - - -or- - + is set to "anonymous". + + -or- + is not a valid value. @@ -407,15 +407,15 @@ One of the enumeration values that determines how to open or create the pipe. Initializes a new instance of the class with the specified pipe and server names, and the specified pipe direction and pipe options. - value of . - -- A default value of . - + value of . + +- A default value of . + ]]> @@ -423,14 +423,14 @@ or is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + is not a valid value. @@ -488,11 +488,11 @@ One of the enumeration values that determines the security impersonation level. Initializes a new instance of the class with the specified pipe and server names, and the specified pipe direction, pipe options, and security impersonation level. - value of . - + value of . + ]]> @@ -500,18 +500,18 @@ or is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - - is not a valid value. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + + is not a valid value. + + -or- + is not a valid value. @@ -558,11 +558,11 @@ One of the enumeration values that determines whether the underlying handle will be inheritable by child processes. Initializes a new instance of the class with the specified pipe and server names, and the specified pipe options, security impersonation level, and inheritability mode. - , the pipe direction will be . If the value of `desiredAccessRights` is , the pipe direction will be . If the value of `desiredAccessRights` includes both and , the pipe direction will be . - + , the pipe direction will be . If the value of `desiredAccessRights` is , the pipe direction will be . If the value of `desiredAccessRights` includes both and , the pipe direction will be . + ]]> @@ -570,18 +570,18 @@ or is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - - is not a valid value. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + + is not a valid value. + + -or- + is not a valid value. @@ -641,22 +641,22 @@ or is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - - is not a valid value. - - -or- - - is not a valid value. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + + is not a valid value. + + -or- + + is not a valid value. + + -or- + is not a valid value. @@ -755,23 +755,23 @@ Connects to a waiting server with an infinite time-out value. - method with an infinite time-out value. - - This method waits for a pipe instance to become available. might return before is called from the object, but will not return until has returned. - - Any data written to the pipe after a object has connected, but before the server has called , will be available to the server following the call to . - - - -## Examples - The following example demonstrates a method to send a string from a parent process to a child process using named pipes. This example creates a object in a child process, which then connects to a pipe on the local computer. The server example can be seen in the class. This example is part of a larger example provided for the and classes. - + method with an infinite time-out value. + + This method waits for a pipe instance to become available. might return before is called from the object, but will not return until has returned. + + Any data written to the pipe after a object has connected, but before the server has called , will be available to the server following the call to . + + + +## Examples + The following example demonstrates a method to send a string from a parent process to a child process using named pipes. This example creates a object in a child process, which then connects to a pipe on the local computer. The server example can be seen in the class. This example is part of a larger example provided for the and classes. + :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/NamedPipeClientStream/Overview/Program.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeClientStream_Sample1/vb/program.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeClientStream_Sample1/vb/program.vb" id="Snippet01"::: + ]]> The client is already connected. @@ -822,13 +822,13 @@ The number of milliseconds to wait for the server to respond before the connection times out. Connects to a waiting server within the specified time-out period. - might return before is called from the , but will not return until has returned. You set the `timeout` parameter to to specify an infinite time-out value. - - Any data written to the pipe after a object has connected, but before the server has called , will be available to the server following the call to . - + might return before is called from the , but will not return until has returned. You set the `timeout` parameter to to specify an infinite time-out value. + + Any data written to the pipe after a object has connected, but before the server has called , will be available to the server following the call to . + ]]> Could not connect to the server within the specified period. @@ -993,6 +993,7 @@ Asynchronously connects to a waiting server and monitors cancellation requests. A task that represents the asynchronous connect operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1036,6 +1037,7 @@ Asynchronously connects to a waiting server within the specified timeout period and monitors cancellation requests. A task that represents the asynchronous connect operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1066,6 +1068,7 @@ Asynchronously connects to a waiting server within the specified timeout period and monitors cancellation requests. A task that represents the asynchronous connect operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1150,25 +1153,25 @@ Gets the number of server instances that share the same pipe name. The number of server instances that share the same pipe name. - object that the current object has a handle to or is connected to. If the current object has not yet connected to a named pipe server, or if the current pipe handle has not yet been set, this property throws an . - - - -## Examples - The following example demonstrates a method to send a string from a parent process to a child process using named pipes. In this example, a object is created in a child process, which then connects to a pipe on the local computer. The server example can be seen in the class. This example is part of a larger example provided for the and classes. - + object that the current object has a handle to or is connected to. If the current object has not yet connected to a named pipe server, or if the current pipe handle has not yet been set, this property throws an . + + + +## Examples + The following example demonstrates a method to send a string from a parent process to a child process using named pipes. In this example, a object is created in a child process, which then connects to a pipe on the local computer. The server example can be seen in the class. This example is part of a larger example provided for the and classes. + :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/NamedPipeClientStream/Overview/Program.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeClientStream_Sample1/vb/program.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeClientStream_Sample1/vb/program.vb" id="Snippet01"::: + ]]> - The pipe handle has not been set. - - -or- - + The pipe handle has not been set. + + -or- + The current object has not yet connected to a object. The pipe is broken or an I/O error occurred. The underlying pipe handle is closed. diff --git a/xml/System.IO.Pipes/NamedPipeServerStream.xml b/xml/System.IO.Pipes/NamedPipeServerStream.xml index 8f36106eeff..b89475e06ff 100644 --- a/xml/System.IO.Pipes/NamedPipeServerStream.xml +++ b/xml/System.IO.Pipes/NamedPipeServerStream.xml @@ -39,21 +39,21 @@ Exposes a around a named pipe, supporting both synchronous and asynchronous read and write operations. - objects. - - Any process can act as either a named pipe server or client, or both. - -## Examples - The following example demonstrates a way to send a string from a parent process to a child process on the same computer using named pipes. This example creates a object in a parent process with a value of . The server then waits for a object in a child process to connect to it. In this example, both processes are on the same computer and the object has a value of . The parent process then sends a user-supplied string to the child process. The string is displayed to the console. - - This example is for the server process, which uses the class. For the entire code example, including the code for both the pipe client and server, see [How to: Use Named Pipes for Network Interprocess Communication](/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication). - + objects. + + Any process can act as either a named pipe server or client, or both. + +## Examples + The following example demonstrates a way to send a string from a parent process to a child process on the same computer using named pipes. This example creates a object in a parent process with a value of . The server then waits for a object in a child process to connect to it. In this example, both processes are on the same computer and the object has a value of . The parent process then sends a user-supplied string to the child process. The string is displayed to the console. + + This example is for the server process, which uses the class. For the entire code example, including the code for both the pipe client and server, see [How to: Use Named Pipes for Network Interprocess Communication](/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication). + :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/NamedPipeServerStream/Overview/Program.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_Sample1/vb/program.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_Sample1/vb/program.vb" id="Snippet01"::: + ]]> @@ -114,27 +114,27 @@ The name of the pipe. Initializes a new instance of the class with the specified pipe name. - object that has the following characteristics: - -- A default pipe direction of . - -- The maximum number of server instances that share the same name set to 1. - -- A value of . - -- A value of . - -- Default input and output buffer sizes. - -- No pipe security. - -- A value of . - -- No specified additional . - + object that has the following characteristics: + +- A default pipe direction of . + +- The maximum number of server instances that share the same name set to 1. + +- A value of . + +- A value of . + +- Default input and output buffer sizes. + +- No pipe security. + +- A value of . + +- No specified additional . + ]]> @@ -196,31 +196,31 @@ One of the enumeration values that determines the direction of the pipe. Initializes a new instance of the class with the specified pipe name and pipe direction. - object that has the following characteristics: - -- A value of . - -- A value of . - -- Default input and output buffer sizes. - -- No pipe security. - -- A value of . - -- No specified additional . - - - -## Examples - The following example demonstrates a method to send a string from a parent process to a child process using named pipes. This example creates a object in a parent process. The object has a value of , which then blocks until a object establishes a connection to the current object. - + object that has the following characteristics: + +- A value of . + +- A value of . + +- Default input and output buffer sizes. + +- No pipe security. + +- A value of . + +- No specified additional . + + + +## Examples + The following example demonstrates a method to send a string from a parent process to a child process using named pipes. This example creates a object in a parent process. The object has a value of , which then blocks until a object establishes a connection to the current object. + :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/NamedPipeServerStream/Overview/Program.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_Sample1/vb/program.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_Sample1/vb/program.vb" id="Snippet01"::: + ]]> @@ -228,10 +228,10 @@ is a zero-length string. - is set to "anonymous". - - -or- - + is set to "anonymous". + + -or- + is not a valid value. contains a colon (":"). @@ -288,25 +288,25 @@ The maximum number of server instances that share the same name. You can pass for this value. Initializes a new instance of the class with the specified pipe name, pipe direction, and maximum number of server instances. - object that has the following characteristics: - -- A default value of 1 for the maximum number of server instances that share the same name. - -- A default value of . - -- A value of . - -- Default input and output buffer sizes. - -- No pipe security. - -- A value of . - -- No specified additional . - + object that has the following characteristics: + +- A default value of 1 for the maximum number of server instances that share the same name. + +- A default value of . + +- A value of . + +- Default input and output buffer sizes. + +- No pipe security. + +- A value of . + +- No specified additional . + ]]> @@ -314,26 +314,26 @@ is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - - A non-negative number is required. - - -or- - - is less than -1 or greater than 254 (-1 indicates ) - - -or- - - or is required. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + + A non-negative number is required. + + -or- + + is less than -1 or greater than 254 (-1 indicates ) + + -or- + + or is required. + + -or- + Access rights is limited to the , , and flags. contains a colon (":"). @@ -401,10 +401,10 @@ is an invalid handle. - is not a valid pipe handle. - - -or- - + is not a valid pipe handle. + + -or- + The maximum number of server instances has been exceeded. @@ -460,21 +460,21 @@ One of the enumeration values that determines the transmission mode of the pipe. Initializes a new instance of the class with the specified pipe name, pipe direction, maximum number of server instances, and transmission mode. - object that has the following characteristics: - -- A default value of . - -- Default input and output buffer sizes. - -- No pipe security. - -- A value of . - -- No specified additional . - + object that has the following characteristics: + +- A default value of . + +- Default input and output buffer sizes. + +- No pipe security. + +- A value of . + +- No specified additional . + ]]> @@ -482,14 +482,14 @@ is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + is less than -1 or greater than 254 (-1 indicates ) contains a colon (":"). @@ -550,19 +550,19 @@ One of the enumeration values that determines how to open or create the pipe. Initializes a new instance of the class with the specified pipe name, pipe direction, maximum number of server instances, transmission mode, and pipe options. - object that has the following characteristics: - -- Default input and output buffer sizes. - -- No pipe security. - -- A value of . - -- No specified additional . - + object that has the following characteristics: + +- Default input and output buffer sizes. + +- No pipe security. + +- A value of . + +- No specified additional . + ]]> @@ -570,18 +570,18 @@ is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - - is less than -1 or greater than 254 (-1 indicates ) - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + + is less than -1 or greater than 254 (-1 indicates ) + + -or- + is not a valid value. contains a colon (":"). @@ -646,17 +646,17 @@ A positive value greater than 0 that indicates the output buffer size. Initializes a new instance of the class with the specified pipe name, pipe direction, maximum number of server instances, transmission mode, pipe options, and recommended in and out buffer sizes. - object that has the following characteristics: - -- No additional pipe security. - -- A default value of . - -- No specified additional . - + object that has the following characteristics: + +- No additional pipe security. + +- A default value of . + +- No specified additional . + ]]> @@ -664,22 +664,22 @@ is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - - is less than -1 or greater than 254 (-1 indicates ) - - -or- - - is not a valid value. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + + is less than -1 or greater than 254 (-1 indicates ) + + -or- + + is not a valid value. + + -or- + is negative. contains a colon (":"). @@ -737,15 +737,15 @@ An object that determines the access control and audit security for the pipe. Initializes a new instance of the class with the specified pipe name, pipe direction, maximum number of server instances, transmission mode, pipe options, recommended in and out buffer sizes, and pipe security. - object that has the following characteristics: - -- A default value of . - -- No specified additional . - + object that has the following characteristics: + +- A default value of . + +- No specified additional . + ]]> @@ -753,22 +753,22 @@ is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - - is less than -1 or greater than 254 (-1 indicates ) - - -or- - - is not a valid value. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + + is less than -1 or greater than 254 (-1 indicates ) + + -or- + + is not a valid value. + + -or- + is negative. contains a colon (":"). @@ -828,11 +828,11 @@ One of the enumeration values that determines whether the underlying handle can be inherited by child processes. Initializes a new instance of the class with the specified pipe name, pipe direction, maximum number of server instances, transmission mode, pipe options, recommended in and out buffer sizes, pipe security, and inheritability mode. - object that has no specified additional . - + object that has no specified additional . + ]]> @@ -840,26 +840,26 @@ is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - - is less than -1 or greater than 254 (-1 indicates ) - - -or- - - is not a valid value. - - -or- - - is negative. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + + is less than -1 or greater than 254 (-1 indicates ) + + -or- + + is not a valid value. + + -or- + + is negative. + + -or- + is not a valid value. contains a colon (":"). @@ -926,30 +926,30 @@ is a zero-length string. - is set to "anonymous". - - -or- - - is not a valid value. - - -or- - - is less than -1 or greater than 254 (-1 indicates ) - - -or- - - is not a valid value. - - -or- - - is negative. - - -or- - - is not a valid value. - - -or- - + is set to "anonymous". + + -or- + + is not a valid value. + + -or- + + is less than -1 or greater than 254 (-1 indicates ) + + -or- + + is not a valid value. + + -or- + + is negative. + + -or- + + is not a valid value. + + -or- + is not a valid value. contains a colon (":"). @@ -1004,23 +1004,23 @@ Begins an asynchronous operation to wait for a client to connect. An object that references the asynchronous request. - . - - must be called exactly once for every call to . - + . + + must be called exactly once for every call to . + ]]> - The pipe was not opened asynchronously. - - -or- - - A pipe connection has already been established. - - -or- - + The pipe was not opened asynchronously. + + -or- + + A pipe connection has already been established. + + -or- + The pipe handle has not been set. The pipe connection has been broken. The pipe is closed. @@ -1068,21 +1068,21 @@ Disconnects the current connection. - method will block until all the sent characters have been read unless the transmission mode of the pipe is set to and the buffer size is set in the constructor that created the object. In this case, not all of the messages will be received. Calling causes the server to block until all the data has been read from the pipe. - + method will block until all the sent characters have been read unless the transmission mode of the pipe is set to and the buffer size is set in the constructor that created the object. In this case, not all of the messages will be received. Calling causes the server to block until all the data has been read from the pipe. + ]]> - No pipe connections have been made yet. - - -or- - - The connected pipe has already disconnected. - - -or- - + No pipe connections have been made yet. + + -or- + + The connected pipe has already disconnected. + + -or- + The pipe handle has not been set. The pipe is closed. @@ -1131,19 +1131,19 @@ The pending asynchronous request. Ends an asynchronous operation to wait for a client to connect. - must be called exactly once for every call to . - + must be called exactly once for every call to . + ]]> is . - The pipe was not opened asynchronously. - - -or- - + The pipe was not opened asynchronously. + + -or- + The pipe handle has not been set. The pipe connection has been broken. The pipe is closed. @@ -1228,36 +1228,36 @@ Gets the user name of the client on the other end of the pipe. The user name of the client on the other end of the pipe. - method returns `null` if the client has not yet written to the pipe or if the connected client did not connect with a of . - - - -## Examples - The following example demonstrates a method to create a pipe server that can respond to multiple simultaneous client requests, and a method for client impersonation. This example creates a object in a parent process, which then creates multiple threads that wait for objects to connect. After a client is connected, it supplies a file name to the server and the contents of that file are read and sent back to the client. Because the impersonates the client when opening the file, the client can request only files that it has sufficient permissions to open. - + method returns `null` if the client has not yet written to the pipe or if the connected client did not connect with a of . + + + +## Examples + The following example demonstrates a method to create a pipe server that can respond to multiple simultaneous client requests, and a method for client impersonation. This example creates a object in a parent process, which then creates multiple threads that wait for objects to connect. After a client is connected, it supplies a file name to the server and the contents of that file are read and sent back to the client. Because the impersonates the client when opening the file, the client can request only files that it has sufficient permissions to open. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/cpp/program.cpp" id="Snippet01"::: :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/NamedPipeServerStream/GetImpersonationUserName/Program.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/vb/program.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/vb/program.vb" id="Snippet01"::: + ]]> - No pipe connections have been made yet. - - -or- - - The connected pipe has already disconnected. - - -or- - + No pipe connections have been made yet. + + -or- + + The connected pipe has already disconnected. + + -or- + The pipe handle has not been set. The pipe is closed. - The pipe connection has been broken. - - -or- - + The pipe connection has been broken. + + -or- + The user name of the client is longer than 19 characters. @@ -1296,11 +1296,11 @@ Represents the maximum number of server instances that the system resources allow. - when creating a object to set the maximum number of server instances that the system resources allow. - + when creating a object to set the maximum number of server instances that the system resources allow. + ]]> @@ -1349,36 +1349,36 @@ The delegate that specifies a method to call. Calls a delegate while impersonating the client. - object in a parent process, which then creates multiple threads that wait for objects to connect. After a client is connected, it supplies a file name to the server and the contents of that file are read and sent back to the client. Because the impersonates the client when opening the file, the client can request only files that it has sufficient permissions to open. - + object in a parent process, which then creates multiple threads that wait for objects to connect. After a client is connected, it supplies a file name to the server and the contents of that file are read and sent back to the client. Because the impersonates the client when opening the file, the client can request only files that it has sufficient permissions to open. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/cpp/program.cpp" id="Snippet01"::: :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/NamedPipeServerStream/GetImpersonationUserName/Program.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/vb/program.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/vb/program.vb" id="Snippet01"::: + ]]> - No pipe connections have been made yet. - - -or- - - The connected pipe has already disconnected. - - -or- - + No pipe connections have been made yet. + + -or- + + The connected pipe has already disconnected. + + -or- + The pipe handle has not been set. The pipe is closed. - The pipe connection has been broken. - - -or- - + The pipe connection has been broken. + + -or- + An I/O error occurred. @@ -1424,25 +1424,25 @@ Waits for a client to connect to this object. - object to block until a client connects. - - - -## Examples - The following example demonstrates a method to send a string from a parent process to a child process using named pipes. This example creates a object in a parent process. This object has a value of , which then blocks until a object establishes a connection to the object. This example is part of a larger example provided for the and classes. - + object to block until a client connects. + + + +## Examples + The following example demonstrates a method to send a string from a parent process to a child process using named pipes. This example creates a object in a parent process. This object has a value of , which then blocks until a object establishes a connection to the object. This example is part of a larger example provided for the and classes. + :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/NamedPipeServerStream/Overview/Program.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_Sample1/vb/program.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_Sample1/vb/program.vb" id="Snippet01"::: + ]]> - A pipe connection has already been established. - - -or- - + A pipe connection has already been established. + + -or- + The pipe handle has not been set. The pipe is closed. The pipe connection has been broken. @@ -1494,11 +1494,11 @@ Asynchronously waits for a client to connect to this object. A task that represents the asynchronous wait operation. - or . - + or . + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1544,17 +1544,18 @@ Asynchronously waits for a client to connect to this object and monitors cancellation requests. A task that represents the asynchronous wait operation. - or . - - Cancellation requests using the cancellation token will only work if the object was created with a pipe option value of or if the cancellation occurs before the method is called. - + or . + + Cancellation requests using the cancellation token will only work if the object was created with a pipe option value of or if the cancellation occurs before the method is called. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO.Pipes/PipeStream.xml b/xml/System.IO.Pipes/PipeStream.xml index 4fed3a1af6e..f43b58b93b9 100644 --- a/xml/System.IO.Pipes/PipeStream.xml +++ b/xml/System.IO.Pipes/PipeStream.xml @@ -39,13 +39,13 @@ Exposes a object around a pipe, which supports both anonymous and named pipes. - class provides the base class for named and anonymous pipes operations in the .NET Framework. Use the and classes for named pipe operations. Use the and classes for anonymous pipe operations. - - For more information about pipes, see [Pipes](/dotnet/standard/io/pipe-operations). For an example of anonymous pipes, see [How to: Use Anonymous Pipes for Local Interprocess Communication](/dotnet/standard/io/how-to-use-anonymous-pipes-for-local-interprocess-communication). For an example of named pipes, see [How to: Use Named Pipes for Network Interprocess Communication](/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication). - + class provides the base class for named and anonymous pipes operations in the .NET Framework. Use the and classes for named pipe operations. Use the and classes for anonymous pipe operations. + + For more information about pipes, see [Pipes](/dotnet/standard/io/pipe-operations). For an example of anonymous pipes, see [How to: Use Anonymous Pipes for Local Interprocess Communication](/dotnet/standard/io/how-to-use-anonymous-pipes-for-local-interprocess-communication). For an example of named pipes, see [How to: Use Named Pipes for Network Interprocess Communication](/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication). + ]]> @@ -98,18 +98,18 @@ A positive value greater than or equal to 0 that indicates the buffer size. Initializes a new instance of the class using the specified value and buffer size. - . - + . + ]]> - is not a valid value. - - -or- - + is not a valid value. + + -or- + is less than 0. @@ -154,14 +154,14 @@ Initializes a new instance of the class using the specified , , and buffer size. To be added. - is not a valid value. - - -or- - - is not a valid value. - - -or- - + is not a valid value. + + -or- + + is not a valid value. + + -or- + is less than 0. @@ -219,24 +219,24 @@ Begins an asynchronous read operation. An object that references the asynchronous read. - object to the method to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . This can be done either in the same code that called or in a callback that is passed to . - - Use the property to determine whether the current object supports read operations. - - If the pipe is closed or an invalid argument is passed to , the appropriate exceptions are raised immediately. Errors that occur during an asynchronous read request occur on the thread pool thread that is performing the request. The exceptions are raised when the code calls the method. - + object to the method to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . This can be done either in the same code that called or in a callback that is passed to . + + Use the property to determine whether the current object supports read operations. + + If the pipe is closed or an invalid argument is passed to , the appropriate exceptions are raised immediately. Errors that occur during an asynchronous read request occur on the thread pool thread that is performing the request. The exceptions are raised when the code calls the method. + ]]> is . - is less than 0. - - -or- - + is less than 0. + + -or- + is less than 0. is greater than the number of bytes available in . @@ -300,24 +300,24 @@ Begins an asynchronous write operation. An object that references the asynchronous write operation. - must be called once for every call to . This can be done either in the same code that called or in a callback that is passed to . - - Use the property to determine whether the current object supports write operations. - - If the pipe is closed or an invalid argument is passed to , the appropriate exceptions are raised immediately. Errors that occur during an asynchronous write request occur on the thread pool thread that is performing the request. The exceptions are raised when the code calls the method. - + must be called once for every call to . This can be done either in the same code that called or in a callback that is passed to . + + Use the property to determine whether the current object supports write operations. + + If the pipe is closed or an invalid argument is passed to , the appropriate exceptions are raised immediately. Errors that occur during an asynchronous write request occur on the thread pool thread that is performing the request. The exceptions are raised when the code calls the method. + ]]> is . - is less than 0. - - -or- - + is less than 0. + + -or- + is less than 0. is greater than the number of bytes available in . @@ -370,11 +370,11 @@ if the stream supports read operations; otherwise, . - object is closed, this property returns `false`. - + object is closed, this property returns `false`. + ]]> @@ -416,11 +416,11 @@ in all cases. - object is closed, this property returns `false`. - + object is closed, this property returns `false`. + ]]> @@ -468,11 +468,11 @@ if the stream supports write operations; otherwise, . - object is closed, this property returns `false`. - + object is closed, this property returns `false`. + ]]> @@ -652,20 +652,20 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the class and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. - -When the disposing parameter is `true`, this method releases all resources held by any managed objects that this object references. This method invokes the method of each referenced object. - + +When the disposing parameter is `true`, this method releases all resources held by any managed objects that this object references. This method invokes the method of each referenced object. + ]]> - In derived classes, put all cleanup logic in the method. - - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + In derived classes, put all cleanup logic in the method. + + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). @@ -715,17 +715,17 @@ When the disposing parameter is `true`, this method releases all resources held Ends a pending asynchronous read request. The number of bytes that were read. A return value of 0 indicates the end of the stream (the pipe has been closed). - . - - Pass the returned object to the method to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . This can be done either in the same code that called or in a callback that is passed to . - - Use the property to determine whether the current object supports read operations. - - If the pipe is closed or an invalid argument is passed to , the appropriate exceptions are raised immediately. Errors that occur during an asynchronous read request occur on the thread pool thread that is performing the request. The exceptions are raised when the code calls the method. - + . + + Pass the returned object to the method to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . This can be done either in the same code that called or in a callback that is passed to . + + Use the property to determine whether the current object supports read operations. + + If the pipe is closed or an invalid argument is passed to , the appropriate exceptions are raised immediately. Errors that occur during an asynchronous read request occur on the thread pool thread that is performing the request. The exceptions are raised when the code calls the method. + ]]> @@ -779,15 +779,15 @@ When the disposing parameter is `true`, this method releases all resources held The reference to the pending asynchronous request. Ends a pending asynchronous write request. - must be called once for every call to . This can be done either in the same code that called or in a callback that is passed to . - - Use the property to determine whether the current object supports write operations. - - If the pipe is closed or an invalid argument is passed to , the appropriate exceptions are raised immediately. Errors that occur during an asynchronous write request occur on the thread pool thread that is performing the request. The exceptions are raised when the code the calls method. - + must be called once for every call to . This can be done either in the same code that called or in a callback that is passed to . + + Use the property to determine whether the current object supports write operations. + + If the pipe is closed or an invalid argument is passed to , the appropriate exceptions are raised immediately. Errors that occur during an asynchronous write request occur on the thread pool thread that is performing the request. The exceptions are raised when the code the calls method. + ]]> @@ -839,11 +839,11 @@ When the disposing parameter is `true`, this method releases all resources held Clears the buffer for the current stream and causes any buffered data to be written to the underlying device. - method is not supported in the class and does nothing when it is called. - + method is not supported in the class and does nothing when it is called. + ]]> The pipe is closed. @@ -879,6 +879,7 @@ When the disposing parameter is `true`, this method releases all resources held Asynchronously clears the buffer for the current stream and causes any buffered data to be written to the underlying device. A task that represent the asynchronous flush operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -915,11 +916,11 @@ When the disposing parameter is `true`, this method releases all resources held Gets a object that encapsulates the access control list (ACL) entries for the pipe described by the current object. A object that encapsulates the access control list (ACL) entries for the pipe described by the current object. - The pipe is closed. @@ -970,11 +971,11 @@ When the disposing parameter is `true`, this method releases all resources held Gets the size, in bytes, of the inbound buffer for a pipe. An integer value that represents the inbound buffer size, in bytes. - is 0, the buffer size is allocated as needed. - + is 0, the buffer size is allocated as needed. + ]]> The stream is unreadable. @@ -1033,11 +1034,11 @@ When the disposing parameter is `true`, this method releases all resources held to indicate that the handle was opened asynchronously; otherwise, . Initializes a object from the specified object. - property to `true`. - + property to `true`. + ]]> A handle cannot be bound to the pipe. @@ -1086,11 +1087,11 @@ When the disposing parameter is `true`, this method releases all resources held if the object was opened asynchronously; otherwise, . - property correctly. - + property correctly. + ]]> @@ -1132,11 +1133,11 @@ When the disposing parameter is `true`, this method releases all resources held if the object is connected; otherwise, . - property returns `true` only if the object is connected. If this property returns `false`, the pipe may be waiting to connect, or may be disconnected, closed, or broken. - + property returns `true` only if the object is connected. If this property returns `false`, the pipe may be waiting to connect, or may be disconnected, closed, or broken. + ]]> @@ -1183,11 +1184,11 @@ When the disposing parameter is `true`, this method releases all resources held if a handle to the object is exposed; otherwise, . - object. - + object. + ]]> @@ -1235,21 +1236,21 @@ When the disposing parameter is `true`, this method releases all resources held if there are no more characters to read in the message; otherwise, . - property was set to by the most recent call to or . - + property was set to by the most recent call to or . + ]]> - The pipe is not connected. - - -or- - - The pipe handle has not been set. - - -or- - + The pipe is not connected. + + -or- + + The pipe handle has not been set. + + -or- + The pipe's property value is not . The pipe is closed. @@ -1290,11 +1291,11 @@ When the disposing parameter is `true`, this method releases all resources held Gets the length of a stream, in bytes. 0 in all cases. - class does not support the property. - + class does not support the property. + ]]> Always thrown. @@ -1342,11 +1343,11 @@ When the disposing parameter is `true`, this method releases all resources held Gets the size, in bytes, of the outbound buffer for a pipe. The outbound buffer size, in bytes. - is 0, the buffer size is allocated as needed. - + is 0, the buffer size is allocated as needed. + ]]> The stream is unwriteable. @@ -1390,11 +1391,11 @@ When the disposing parameter is `true`, this method releases all resources held Gets or sets the current position of the current stream. 0 in all cases. - class does not support the property. - + class does not support the property. + ]]> Always thrown. @@ -1518,31 +1519,31 @@ The pipe handle has not been set. (Did your . This might be less than the number of bytes requested if that number of bytes is not currently available, or 0 if the end of the stream is reached. - property to determine whether the current object supports read operations. - - Calling the method blocks until `count` bytes are read or the end of the stream is reached. For asynchronous read operations, see and . - - - -## Examples - The following example creates an anonymous pipe client and pipe server. The pipe server uses the method to read a series of bytes from the pipe client as a validation code. Both the pipe client and the pipe server are part of the same example. The server portion of the example creates a client process and passes it an anonymous pipe handle as an argument. - + property to determine whether the current object supports read operations. + + Calling the method blocks until `count` bytes are read or the end of the stream is reached. For asynchronous read operations, see and . + + + +## Examples + The following example creates an anonymous pipe client and pipe server. The pipe server uses the method to read a series of bytes from the pipe client as a validation code. Both the pipe client and the pipe server are part of the same example. The server portion of the example creates a client process and passes it an anonymous pipe handle as an argument. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.io.pipes.pipestream/cpp/sample.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO.Pipes/PipeStream/Read/sample.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.pipes.pipestream/vb/sample.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.pipes.pipestream/vb/sample.vb" id="Snippet1"::: + ]]> is . - is less than 0. - - -or- - + is less than 0. + + -or- + is less than 0. is greater than the number of bytes available in . @@ -1584,15 +1585,15 @@ The pipe handle has not been set. (Did your property contains the total number of bytes read into the buffer. The result value can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or it can be 0 (zero) if the end of the stream has been reached. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in applications where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. +The method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in applications where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. -Use the property to determine whether the current instance supports reading. +Use the property to determine whether the current instance supports reading. -If the operation is canceled before it completes, the returned task contains the value for the property. +If the operation is canceled before it completes, the returned task contains the value for the property. ]]> @@ -1600,7 +1601,7 @@ If the operation is canceled before it completes, the returned task contains the Cannot access a closed pipe. The pipe hasn't been connected yet. --or- +-or- The pipe is in a disconnected state. @@ -1608,6 +1609,7 @@ The pipe is in a disconnected state. The pipe handle has not been set. (Did your implementation call ? + The cancellation token was canceled. This exception is stored into the returned task. @@ -1649,7 +1651,7 @@ The pipe handle has not been set. (Did your property contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - implementation call ? + The cancellation token was canceled. This exception is stored into the returned task. @@ -1720,11 +1723,11 @@ The pipe handle has not been set. (Did your , or -1 indicates the end of the stream (the pipe has been closed). - property to determine whether the current object supports read operations. - + property to determine whether the current object supports read operations. + ]]> The pipe is closed. @@ -1779,21 +1782,21 @@ The pipe handle has not been set. (Did your object. One of the values that indicates how the object reads from the pipe. - mode message transmission. + mode message transmission. To avoid an accessing `ReadMode`, can be used to verify the pipe is connected. - + ]]> The supplied value is not a valid value. The supplied value is not a supported value for this pipe stream. - The handle has not been set. - - -or- - + The handle has not been set. + + -or- + The pipe is waiting to connect with a named client. The pipe is broken or an I/O error occurred with a named client. @@ -1886,11 +1889,11 @@ The pipe handle has not been set. (Did your method is not supported in pipes and raises a when it is called. - + method is not supported in pipes and raises a when it is called. + ]]> @@ -1931,11 +1934,11 @@ The pipe handle has not been set. (Did your A object that specifies an access control list (ACL) entry to apply to the current pipe. Applies the access control list (ACL) entries specified by a object to the pipe specified by the current object. - The pipe is closed. @@ -1985,11 +1988,11 @@ The pipe handle has not been set. (Did your The new length of the stream. Sets the length of the current stream to the specified value. - class does not support the method. - + class does not support the method. + ]]> @@ -2036,18 +2039,18 @@ The pipe handle has not been set. (Did your values that indicates the transmission mode supported by the current pipe. - mode message transmission. - + mode message transmission. + ]]> The pipe is closed. - The handle has not been set. - - -or- - + The handle has not been set. + + -or- + The pipe is waiting to connect in an anonymous client/server operation or with a named client. The pipe is broken or another I/O error occurred. @@ -2098,11 +2101,11 @@ The pipe handle has not been set. (Did your method blocks until the other end of the pipe has read all sent bytes. - + method blocks until the other end of the pipe has read all sent bytes. + ]]> The pipe is closed. @@ -2140,13 +2143,13 @@ The pipe handle has not been set. (Did your A region of memory. This method copies the contents of this region to the current stream. Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. - property to determine whether the current instance supports writing. Use the method to write asynchronously to the current stream. +Use the property to determine whether the current instance supports writing. Use the method to write asynchronously to the current stream. -If the write operation is successful, the position within the stream advances by the number of bytes written. If an exception occurs, the position within the stream remains unchanged. +If the write operation is successful, the position within the stream advances by the number of bytes written. If an exception occurs, the position within the stream remains unchanged. ]]> @@ -2214,22 +2217,22 @@ The pipe handle has not been set. (Did your The maximum number of bytes to write to the current stream. Writes a block of bytes to the current stream using data from a buffer. - property to determine whether the current object supports write operations. - - For asynchronous write operations, see and . - + property to determine whether the current object supports write operations. + + For asynchronous write operations, see and . + ]]> is . - is less than 0. - - -or- - + is less than 0. + + -or- + is less than 0. is greater than the number of bytes available in . @@ -2270,7 +2273,7 @@ The pipe handle has not been set. (Did your implementation call ? + The cancellation token was canceled. This exception is stored into the returned task. @@ -2336,9 +2340,9 @@ The pipe handle has not been set. (Did your method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in applications where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. @@ -2373,6 +2377,7 @@ The pipe is in a disconnected state. The pipe handle has not been set. (Did your implementation call ? + The cancellation token was canceled. This exception is stored into the returned task. @@ -2420,11 +2425,11 @@ The pipe handle has not been set. (Did your The byte to write to the stream. Writes a byte to the current stream. - property to determine whether the current object supports write operations. - + property to determine whether the current object supports write operations. + ]]> The pipe is closed. diff --git a/xml/System.IO/BufferedStream.xml b/xml/System.IO/BufferedStream.xml index 3e88d17fc8c..bcadb68847a 100644 --- a/xml/System.IO/BufferedStream.xml +++ b/xml/System.IO/BufferedStream.xml @@ -60,37 +60,37 @@ Adds a buffering layer to read and write operations on another stream. This class cannot be inherited. - and methods of `BufferedStream` automatically maintain the buffer. - + and methods of `BufferedStream` automatically maintain the buffer. + > [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - - `BufferedStream` can be composed around certain types of streams. It provides implementations for reading and writing bytes to an underlying data source or repository. Use and for reading and writing other data types. `BufferedStream` is designed to prevent the buffer from slowing down input and output when the buffer is not needed. If you always read and write for sizes greater than the internal buffer size, then `BufferedStream` might not even allocate the internal buffer. `BufferedStream` also buffers reads and writes in a shared buffer. It is assumed that you will almost always be doing a series of reads or writes, but rarely alternate between the two of them. - - - -## Examples - The following code examples show how to use the `BufferedStream` class over the `NetworkStream` class to increase the performance of certain I/O operations. Start the server on a remote computer before starting the client. Specify the remote computer name as a command-line argument when starting the client. Vary the `dataArraySize` and `streamBufferSize` constants to view their effect on performance. - - The first example shows the code that runs on the client, and the second example shows the code that runs on the server. - - **Example 1: Code that runs on the client** - +> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. + + `BufferedStream` can be composed around certain types of streams. It provides implementations for reading and writing bytes to an underlying data source or repository. Use and for reading and writing other data types. `BufferedStream` is designed to prevent the buffer from slowing down input and output when the buffer is not needed. If you always read and write for sizes greater than the internal buffer size, then `BufferedStream` might not even allocate the internal buffer. `BufferedStream` also buffers reads and writes in a shared buffer. It is assumed that you will almost always be doing a series of reads or writes, but rarely alternate between the two of them. + + + +## Examples + The following code examples show how to use the `BufferedStream` class over the `NetworkStream` class to increase the performance of certain I/O operations. Start the server on a remote computer before starting the client. Specify the remote computer name as a command-line argument when starting the client. Vary the `dataArraySize` and `streamBufferSize` constants to view their effect on performance. + + The first example shows the code that runs on the client, and the second example shows the code that runs on the server. + + **Example 1: Code that runs on the client** + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.BufferedStream1/CPP/client.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/BufferedStream/Overview/client.cs" id="Snippet1"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO/BufferedStream/Overview/client.fs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet1"::: - - **Example 2: Code that runs on the server** - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet1"::: + + **Example 2: Code that runs on the server** + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.BufferedStream2/CPP/server.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/BufferedStream/Overview/server.cs" id="Snippet1"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO/BufferedStream/Overview/server.fs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream2/VB/server.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream2/VB/server.vb" id="Snippet1"::: + ]]> @@ -153,11 +153,11 @@ The current stream. Initializes a new instance of the class with a default buffer size of 4096 bytes. - @@ -212,21 +212,21 @@ The buffer size in bytes. Initializes a new instance of the class with the specified buffer size. - class. - + class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.BufferedStream1/CPP/client.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/BufferedStream/Overview/client.cs" id="Snippet2"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO/BufferedStream/Overview/client.fs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet2"::: + ]]> @@ -292,18 +292,18 @@ Begins an asynchronous read operation. (Consider using instead.) An object that represents the asynchronous read, which could still be pending. - and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , and , help you implement asynchronous file operations more easily. - - must be called exactly once for every call to . Failing to end a read process before beginning another read can cause undesirable behavior such as deadlock. - + and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , and , help you implement asynchronous file operations more easily. + + must be called exactly once for every call to . Failing to end a read process before beginning another read can cause undesirable behavior such as deadlock. + > [!NOTE] -> Use the property to determine whether the current instance supports reading. - - must be called with this to find out how many bytes were read. - +> Use the property to determine whether the current instance supports reading. + + must be called with this to find out how many bytes were read. + ]]> @@ -369,13 +369,13 @@ Begins an asynchronous write operation. (Consider using instead.) An object that references the asynchronous write which could still be pending. - and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , and , help you implement asynchronous file operations more easily. - - must be called exactly once on every from . will block until the I/O operation has completed. - + and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , and , help you implement asynchronous file operations more easily. + + must be called exactly once on every from . will block until the I/O operation has completed. + ]]> @@ -467,23 +467,23 @@ if the stream supports reading; if the stream is closed or was opened with write-only access. - does not support reading, calls to the , , , , and the `Peek` methods of , , and throw a . - - If the stream is closed, this property returns `false`. - - - -## Examples - This code example is part of a larger example provided for the class. - + does not support reading, calls to the , , , , and the `Peek` methods of , , and throw a . + + If the stream is closed, this property returns `false`. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.BufferedStream1/CPP/client.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.IO/BufferedStream/Overview/client.cs" id="Snippet5"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO/BufferedStream/Overview/client.fs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet5"::: + ]]> @@ -536,23 +536,23 @@ if the stream supports seeking; if the stream is closed or if the stream was constructed from an operating system handle such as a pipe or output to the console. - does not support seeking, calls to , , , and throw a . - - If the stream is closed, this property returns `false`. - - - -## Examples - This code example is part of a larger example provided for the class. - + does not support seeking, calls to , , , and throw a . + + If the stream is closed, this property returns `false`. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.BufferedStream1/CPP/client.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.IO/BufferedStream/Overview/client.cs" id="Snippet3"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO/BufferedStream/Overview/client.fs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet3"::: + ]]> @@ -606,23 +606,23 @@ if the stream supports writing; if the stream is closed or was opened with read-only access. - does not support writing, a call to , , or throws a . - - If the stream is closed, this property returns `false`. - - - -## Examples - This code example is part of a larger example provided for the class. - + does not support writing, a call to , , or throws a . + + If the stream is closed, this property returns `false`. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.BufferedStream1/CPP/client.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.IO/BufferedStream/Overview/client.cs" id="Snippet4"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO/BufferedStream/Overview/client.fs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet4"::: + ]]> @@ -664,19 +664,19 @@ before invoking Close. Following a call to Close, any operations on the buffered stream might raise exceptions. Flushing the stream will not flush its underlying encoder unless you explicitly call or Close. Setting to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. Attempting to manipulate a stream after it has been closed might throw an . -## Examples +## Examples This code example is part of a larger example provided for the class. ```vb -' When bufStream is closed, netStream is in turn -' closed, which in turn shuts down the connection +' When bufStream is closed, netStream is in turn +' closed, which in turn shuts down the connection ' and closes clientSocket. Console.WriteLine(vbCrLf & "Shutting down the connection.") bufStream.Close() @@ -798,13 +798,13 @@ bufStream->Close(); Asynchronously reads the bytes from the current buffered stream and writes them to another stream, using a specified buffer size and cancellation token. A task that represents the asynchronous copy operation. - value for the property. +If the operation is canceled before it completes, the returned task contains the value for the property. Copying begins at the current position in the current stream. @@ -812,6 +812,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -860,7 +861,7 @@ This method stores in the task it returns all non-usage exceptions that the meth to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the buffered stream and optionally releases the managed resources. - Waits for the pending asynchronous read operation to complete. (Consider using instead.) The number of bytes read from the stream, between 0 (zero) and the number of bytes you requested. Streams only return 0 only at the end of the stream, otherwise, they should block until at least 1 byte is available. - and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , and , help you implement asynchronous file operations more easily. - - must be called with this to find out how many bytes were read. - + and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , and , help you implement asynchronous file operations more easily. + + must be called with this to find out how many bytes were read. + ]]> @@ -1023,13 +1024,13 @@ Calling `DisposeAsync` allows the resources used by the The pending asynchronous request. Ends an asynchronous write operation and blocks until the I/O operation is complete. (Consider using instead.) - and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , and , help you implement asynchronous file operations more easily. - - must be called exactly once for every call to . Failing to end a read process before beginning another read operation can cause deadlock or other undesirable behavior. - + and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , and , help you implement asynchronous file operations more easily. + + must be called exactly once for every call to . Failing to end a read process before beginning another read operation can cause deadlock or other undesirable behavior. + ]]> @@ -1080,25 +1081,25 @@ Calling `DisposeAsync` allows the resources used by the Clears all buffers for this stream and causes any buffered data to be written to the underlying device. - . - - If you use the constructor, thus specifying the buffer size while creating the `BufferedStream` object, the content is flushed when it reaches the buffer size. For example, code such as `BufferedStream bs = new BufferedStream(bs, 5)` will flush the content when the buffer size reaches 5 bytes. - - All the read and write methods of `BufferedStream` automatically maintain the buffer, so there is no need to invoke `Flush` when switching back and forth between reading and writing. - - - -## Examples - This code example is part of a larger example provided for the class. - + . + + If you use the constructor, thus specifying the buffer size while creating the `BufferedStream` object, the content is flushed when it reaches the buffer size. For example, code such as `BufferedStream bs = new BufferedStream(bs, 5)` will flush the content when the buffer size reaches 5 bytes. + + All the read and write methods of `BufferedStream` automatically maintain the buffer, so there is no need to invoke `Flush` when switching back and forth between reading and writing. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.BufferedStream1/CPP/client.cpp" id="Snippet6"::: :::code language="csharp" source="~/snippets/csharp/System.IO/BufferedStream/Overview/client.cs" id="Snippet6"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO/BufferedStream/Overview/client.fs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet6"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet6"::: + ]]> The stream has been disposed. @@ -1155,6 +1156,7 @@ Calling `DisposeAsync` allows the resources used by the A task that represents the asynchronous flush operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . The stream has been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1251,15 +1253,15 @@ Calling `DisposeAsync` allows the resources used by the Gets the position within the current stream. The position within the current stream. - to obtain the current position within the underlying stream and then adjusts this value according to the current position within the buffer. - - The `set` accessor copies any data previously written to the buffer to the underlying stream, and then invokes . - - Seeking to any location beyond the length of the stream is supported. - + to obtain the current position within the underlying stream and then adjusts this value according to the current position within the buffer. + + The `set` accessor copies any data previously written to the buffer to the underlying stream, and then invokes . + + Seeking to any location beyond the length of the stream is supported. + ]]> The value passed to is negative. @@ -1309,8 +1311,8 @@ Calling `DisposeAsync` allows the resources used by the Copies bytes from the current buffered stream to a byte span and advances the position within the buffered stream by the number of bytes read. The total number of bytes read into the buffer. This can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. - property to determine whether the current instance supports reading. Use the method to read asynchronously from the current stream. @@ -1388,23 +1390,23 @@ Use for reading primitive data types. Copies bytes from the current buffered stream to an array. The total number of bytes read into . This can be less than the number of bytes requested if that many bytes are not currently available, or 0 if the end of the stream has been reached before any data can be read. - for reading primitive data types. - - - -## Examples - This code example is part of a larger example provided for the class. - + for reading primitive data types. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.BufferedStream1/CPP/client.cpp" id="Snippet7"::: :::code language="csharp" source="~/snippets/csharp/System.IO/BufferedStream/Overview/client.cs" id="Snippet7"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO/BufferedStream/Overview/client.fs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet7"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet7"::: + ]]> Length of minus is less than . @@ -1460,7 +1462,7 @@ Use for reading primitive data types. Asynchronously reads a sequence of bytes from the current buffered stream and advances the position within the buffered stream by the number of bytes read. A task that represents the asynchronous read operation. The value of its property contains the total number of bytes read into the buffer. The result value can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or it can be 0 (zero) if the end of the stream has been reached. - + The cancellation token was canceled. This exception is stored into the returned task. @@ -1525,11 +1528,11 @@ If the operation is canceled before it completes, the returned task contains the Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous read operation. The value of the parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - class and passing the property as the `cancellationToken` parameter. - + class and passing the property as the `cancellationToken` parameter. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1542,6 +1545,7 @@ If the operation is canceled before it completes, the returned task contains the The stream does not support reading. The stream has been disposed. The stream is currently in use by a previous read operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1654,15 +1658,15 @@ If the operation is canceled before it completes, the returned task contains the Sets the position within the current buffered stream. The new position within the current buffered stream. - object is the base stream for a object, calling the method can cause the position of the stream to no longer match the position of the internal buffer in the reader. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. - - Seeking to any location beyond the length of the stream is supported. - + object is the base stream for a object, calling the method can cause the position of the stream to no longer match the position of the internal buffer in the reader. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. + + Seeking to any location beyond the length of the stream is supported. + ]]> The stream is not open or is . @@ -1720,15 +1724,15 @@ If the operation is canceled before it completes, the returned task contains the An integer indicating the desired length of the current buffered stream in bytes. Sets the length of the buffered stream. - @@ -1813,7 +1817,7 @@ If the operation is canceled before it completes, the returned task contains the A region of memory. This method copies the contents of this region to the current buffered stream. Writes a sequence of bytes to the current buffered stream and advances the current position within this buffered stream by the number of bytes written. - The number of bytes to be written to the current buffered stream. Copies bytes to the buffered stream and advances the current position within the buffered stream by the number of bytes written. - class. - + class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.BufferedStream1/CPP/client.cpp" id="Snippet6"::: :::code language="csharp" source="~/snippets/csharp/System.IO/BufferedStream/Overview/client.cs" id="Snippet6"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO/BufferedStream/Overview/client.fs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet6"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BufferedStream1/VB/client.vb" id="Snippet6"::: + ]]> Length of minus is less than . @@ -1964,6 +1968,7 @@ If the operation is canceled before it completes, the returned task contains the ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -2017,11 +2022,11 @@ If the operation is canceled before it completes, the returned task contains the Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. - class and passing the property as the `cancellationToken` parameter. - + class and passing the property as the `cancellationToken` parameter. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -2034,6 +2039,7 @@ If the operation is canceled before it completes, the returned task contains the The stream does not support writing. The stream has been disposed. The stream is currently in use by a previous write operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2082,7 +2088,7 @@ If the operation is canceled before it completes, the returned task contains the A byte to write to the stream. Writes a byte to the current position in the buffered stream. - Asynchronously appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file. A task that represents the asynchronous append operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -395,6 +396,7 @@ Asynchronously appends lines to a file by using a specified encoding, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file. A task that represents the asynchronous append operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -644,6 +646,7 @@ Asynchronously opens a file or creates a file if it does not already exist, appends the specified string to the file, and then closes the file. A task that represents the asynchronous append operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -691,6 +694,7 @@ Asynchronously opens a file or creates the file if it does not already exist, appends the specified string to the file using the specified encoding, and then closes the file. A task that represents the asynchronous append operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -4052,6 +4056,7 @@ The following example moves a file. Asynchronously opens a binary file, reads the contents of the file into a byte array, and then closes the file. A task that represents the asynchronous read operation, which wraps the byte array containing the contents of the file. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -4304,6 +4309,7 @@ The following example moves a file. Asynchronously opens a text file, reads all lines of the file, and then closes the file. A task that represents the asynchronous read operation, which wraps the string array containing all lines of the file. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -4348,6 +4354,7 @@ The following example moves a file. Asynchronously opens a text file, reads all lines of the file with the specified encoding, and then closes the file. A task that represents the asynchronous read operation, which wraps the string array containing all lines of the file. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -4608,6 +4615,7 @@ The following example moves a file. Asynchronously opens a text file, reads all the text in the file, and then closes the file. A task that represents the asynchronous read operation, which wraps the string containing all text in the file. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -4652,6 +4660,7 @@ The following example moves a file. Asynchronously opens a text file, reads all text in the file with the specified encoding, and then closes the file. A task that represents the asynchronous read operation, which wraps the string containing all text in the file. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -4897,6 +4906,7 @@ The following example moves a file. Asynchronously reads the lines of a file. The async enumerable that represents all the lines of the file, or the lines that are the result of a query. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -4931,6 +4941,7 @@ The following example moves a file. Asynchronously reads the lines of a file that has a specified encoding. The async enumerable that represents all the lines of the file, or the lines that are the result of a query. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -6402,6 +6413,7 @@ It is not possible to change the compression status of a o Asynchronously creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten. A task that represents the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -6849,6 +6861,7 @@ It is not possible to change the compression status of a o Asynchronously creates a new file, writes the specified lines to the file, and then closes the file. A task that represents the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -6895,6 +6908,7 @@ It is not possible to change the compression status of a o Asynchronously creates a new file, write the specified lines to the file by using the specified encoding, and then closes the file. A task that represents the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -7150,6 +7164,7 @@ It is not possible to change the compression status of a o Asynchronously creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten. A task that represents the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -7197,6 +7212,7 @@ It is not possible to change the compression status of a o Asynchronously creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. A task that represents the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO/FileStream.xml b/xml/System.IO/FileStream.xml index 5f3eeab2728..833c36c9ce4 100644 --- a/xml/System.IO/FileStream.xml +++ b/xml/System.IO/FileStream.xml @@ -1,6 +1,6 @@ - + @@ -31,6 +31,7 @@ 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -39,6 +40,8 @@ + + @@ -48,6 +51,14 @@ + + [System.Runtime.CompilerServices.Nullable(0)] + [<System.Runtime.CompilerServices.Nullable(0)>] + + + [System.Runtime.CompilerServices.NullableContext(1)] + [<System.Runtime.CompilerServices.NullableContext(1)>] + [System.Runtime.InteropServices.ComVisible(true)] [<System.Runtime.InteropServices.ComVisible(true)>] @@ -56,50 +67,51 @@ Provides a for a file, supporting both synchronous and asynchronous read and write operations. - class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the , , , and methods to perform synchronous operations, or the , , , and methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. buffers input and output for better performance. - + class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the , , , and methods to perform synchronous operations, or the , , , and methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. buffers input and output for better performance. + > [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - - The property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the class using a constructor that has an `isAsync`, `useAsync`, or `options` parameter. When the property is `true`, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the property does not have to be `true` to call the , , or method. When the property is `false` and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously. - - The method supports random access to files. allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the enumeration. - +> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. + + The property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the class using a constructor that has an `isAsync`, `useAsync`, or `options` parameter. When the property is `true`, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the property does not have to be `true` to call the , , or method. When the property is `false` and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously. + + The method supports random access to files. allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the enumeration. + > [!NOTE] -> Disk files always support random access. At the time of construction, the property value is set to `true` or `false` depending on the underlying file type. If the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the property value is `true`. Otherwise, the property value is `false`. - - If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined. - - For directory operations and other file operations, see the , , and classes. The class is a utility class that has static methods primarily for the creation of objects based on file paths. The class creates a stream from a byte array and is similar to the class. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - -## Detection of Stream Position Changes - When a object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. In this case, the cached position in the object and the cached data in the buffer could be compromised. The object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the object. - - If an unexpected change in the handle position is detected in a call to the method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream. - - If an unexpected change in the handle position is detected in a call to the method, the contents of the buffer are discarded and an exception is thrown. - - A object will not have an exclusive hold on its handle when either the property is accessed to expose the handle or the object is given the property in its constructor. - - - -## Examples - The following example demonstrates some of the constructors. - +> Disk files always support random access. At the time of construction, the property value is set to `true` or `false` depending on the underlying file type. If the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the property value is `true`. Otherwise, the property value is `false`. + + If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined. + + For directory operations and other file operations, see the , , and classes. The class is a utility class that has static methods primarily for the creation of objects based on file paths. The class creates a stream from a byte array and is similar to the class. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + +## Detection of Stream Position Changes + When a object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. In this case, the cached position in the object and the cached data in the buffer could be compromised. The object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the object. + + If an unexpected change in the handle position is detected in a call to the method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream. + + If an unexpected change in the handle position is detected in a call to the method, the contents of the buffer are discarded and an exception is thrown. + + A object will not have an exclusive hold on its handle when either the property is accessed to expose the handle or the object is given the property in its constructor. + + + +## Examples + The following example demonstrates some of the constructors. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/FStream Class/CPP/fstream class.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/Overview/fstream class.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/FStream Class/VB/fstream class.vb" id="Snippet1"::: - - The following example shows how to write to a file asynchronously. This code runs in a WPF app that has a TextBlock named UserInput and a button hooked up to a Click event handler that is named Button_Click. The file path needs to be changed to a file that exists on the computer. - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/Overview/fstream class.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/FStream Class/VB/fstream class.vb" id="Snippet1"::: + + The following example shows how to write to a file asynchronously. This code runs in a WPF app that has a TextBlock named UserInput and a button hooked up to a Click event handler that is named Button_Click. The file path needs to be changed to a file that exists on the computer. + :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/Overview/example3.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Asynchronous_File_IO_async/vb/example3.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Asynchronous_File_IO_async/vb/example3.vb" id="Snippet3"::: + ]]> @@ -153,6 +165,7 @@ 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -161,37 +174,37 @@ - - + + A file handle for the file that the current object will encapsulate. A bitwise combination of the enumeration values that sets the and properties of the object. Initializes a new instance of the class for the specified file handle, with the specified read/write permission. - is called, the handle is also closed and the file's handle count is decremented. - - `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. - + is called, the handle is also closed and the file's handle count is decremented. + + `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - `FileShare.Read` is the default for those constructors without a `FileShare` parameter. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + `FileShare.Read` is the default for those constructors without a `FileShare` parameter. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> is not a field of . The caller does not have the required permission. - An I/O error, such as a disk error, occurred. - - -or- - + An I/O error, such as a disk error, occurred. + + -or- + The stream has been closed. The requested is not permitted by the operating system for the specified file handle, such as when is or and the file handle is set for read-only access. File and Stream I/O @@ -227,6 +240,7 @@ 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 System.IO.FileSystem @@ -236,11 +250,11 @@ [System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202")] [<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202")>] - + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>] - + [System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.")] [<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.")>] @@ -258,37 +272,37 @@ - - + + A file handle for the file that the current object will encapsulate. A bitwise combination of the enumeration values that sets the and properties of the object. Initializes a new instance of the class for the specified file handle, with the specified read/write permission. - is called, the handle is also closed and the file's handle count is decremented. - - `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. - + is called, the handle is also closed and the file's handle count is decremented. + + `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - `FileShare.Read` is the default for those constructors without a `FileShare` parameter. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + `FileShare.Read` is the default for those constructors without a `FileShare` parameter. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> is not a field of . The caller does not have the required permission. - An I/O error, such as a disk error, occurred. - - -or- - + An I/O error, such as a disk error, occurred. + + -or- + The stream has been closed. The requested is not permitted by the operating system for the specified file handle, such as when is or and the file handle is set for read-only access. File and Stream I/O @@ -329,6 +343,7 @@ 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -345,48 +360,49 @@ One of the enumeration values that determines how to open or create the file. Initializes a new instance of the class with the specified path and creation mode. - [!NOTE] -> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. - - is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . - - `FileShare.Read` is the default for those constructors without a `FileShare` parameter. - - For constructors without a parameter, if the `mode` parameter is set to , is the default access. Otherwise, the access is set to . - +> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. + + is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . + + `FileShare.Read` is the default for those constructors without a `FileShare` parameter. + + For constructors without a parameter, if the `mode` parameter is set to , is the default access. Otherwise, the access is set to . + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream1/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream1/VB/source.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/source.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream1/VB/source.vb" id="Snippet1"::: + ]]> - .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. - - -or- - + .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. + + -or- + refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment. @@ -396,10 +412,10 @@ The file cannot be found, such as when is or , and the file specified by does not exist. The file must already exist in these modes. specifies a file that is read-only. - An I/O error, such as specifying when the file specified by already exists, occurred. - - -or- - + An I/O error, such as specifying when the file specified by already exists, occurred. + + -or- + The stream has been closed. The specified path is invalid, such as being on an unmapped drive. The specified path, file name, or both exceed the system-defined maximum length. @@ -423,6 +439,7 @@ System.Runtime 6.0.0.0 7.0.0.0 + 8.0.0.0 mscorlib @@ -434,8 +451,8 @@ System.IO.FileSystem - - + + A relative or absolute path for the file that the current instance will encapsulate. @@ -516,6 +533,7 @@ The file was too large (when @@ -524,9 +542,9 @@ The file was too large (when - - + + + A file handle for the file that the current object will encapsulate. @@ -534,30 +552,30 @@ The file was too large (when A positive value greater than 0 indicating the buffer size. The default buffer size is 4096. Initializes a new instance of the class for the specified file handle, with the specified read/write permission, and buffer size. - before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. Alternately, read and write to the handle before calling this `FileStream` constructor. - - `FileShare.Read` is the default for those constructors without a `FileShare` parameter. - + before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. Alternately, read and write to the handle before calling this `FileStream` constructor. + + `FileShare.Read` is the default for those constructors without a `FileShare` parameter. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> - The parameter is an invalid handle. - - -or- - + The parameter is an invalid handle. + + -or- + The parameter is a synchronous handle and it was used asynchronously. The parameter is negative. - An I/O error, such as a disk error, occurred. - - -or- - + An I/O error, such as a disk error, occurred. + + -or- + The stream has been closed. The caller does not have the required permission. The requested is not permitted by the operating system for the specified file handle, such as when is or and the file handle is set for read-only access. @@ -594,6 +612,7 @@ The file was too large (when [System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")] [<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")>] - + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>] - + [System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")] [<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")>] @@ -625,9 +644,9 @@ The file was too large (when - - + + + A file handle for the file that the current object will encapsulate. @@ -636,29 +655,29 @@ The file was too large (when if the file handle will be owned by this instance; otherwise, . Initializes a new instance of the class for the specified file handle, with the specified read/write permission and instance ownership. - method will also close the handle and the file's handle count is decremented. The `FileStream` object is given the default buffer size of 4096 bytes. - - `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling methods other than `Close` after you are done using the handle. - - `FileShare.Read` is the default for those constructors without a `FileShare` parameter. - + method will also close the handle and the file's handle count is decremented. The `FileStream` object is given the default buffer size of 4096 bytes. + + `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling methods other than `Close` after you are done using the handle. + + `FileShare.Read` is the default for those constructors without a `FileShare` parameter. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> is not a field of . The caller does not have the required permission. - An I/O error, such as a disk error, occurred. - - -or- - + An I/O error, such as a disk error, occurred. + + -or- + The stream has been closed. The requested is not permitted by the operating system for the specified file handle, such as when is or and the file handle is set for read-only access. File and Stream I/O @@ -699,6 +718,7 @@ The file was too large (when @@ -717,43 +737,43 @@ The file was too large (when A bitwise combination of the enumeration values that determines how the file can be accessed by the object. This also determines the values returned by the and properties of the object. is if specifies a disk file. Initializes a new instance of the class with the specified path, creation mode, and read/write permission. - [!NOTE] -> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. - - is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . - - `FileShare.Read` is the default for those constructors without a `FileShare` parameter. - +> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. + + is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . + + `FileShare.Read` is the default for those constructors without a `FileShare` parameter. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> is . - .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. - - -or- - + .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. + + -or- + refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment. The file cannot be found, such as when is or , and the file specified by does not exist. The file must already exist in these modes. - An I/O error, such as specifying when the file specified by already exists, occurred. - - -or- - + An I/O error, such as specifying when the file specified by already exists, occurred. + + -or- + The stream has been closed. The caller does not have the required permission. The specified path is invalid, such as being on an unmapped drive. @@ -798,6 +818,7 @@ The file was too large (when @@ -806,10 +827,10 @@ The file was too large (when - - - + + + + A file handle for the file that this object will encapsulate. @@ -819,32 +840,32 @@ The file was too large (when if the handle was opened asynchronously (that is, in overlapped I/O mode); otherwise, . Initializes a new instance of the class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state. - , , or method. When the `isAsync` parameter is `false` and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously. - - `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. Alternately, read and write to the handle before calling this `FileStream` constructor. - - `FileShare.Read` is the default for those constructors without a `FileShare` parameter. - + , , or method. When the `isAsync` parameter is `false` and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously. + + `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. Alternately, read and write to the handle before calling this `FileStream` constructor. + + `FileShare.Read` is the default for those constructors without a `FileShare` parameter. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> - The parameter is an invalid handle. - - -or- - + The parameter is an invalid handle. + + -or- + The parameter is a synchronous handle and it was used asynchronously. The parameter is negative. - An I/O error, such as a disk error, occurred. - - -or- - + An I/O error, such as a disk error, occurred. + + -or- + The stream has been closed. The caller does not have the required permission. The requested is not permitted by the operating system for the specified file handle, such as when is or and the file handle is set for read-only access. @@ -881,6 +902,7 @@ The file was too large (when [System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")] [<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")>] - + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>] - + [System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")] [<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")>] @@ -912,10 +934,10 @@ The file was too large (when - - - + + + + A file handle for the file that this object will encapsulate. @@ -925,28 +947,28 @@ The file was too large (when A positive value greater than 0 indicating the buffer size. The default buffer size is 4096. Initializes a new instance of the class for the specified file handle, with the specified read/write permission, instance ownership, and buffer size. - method will also close the handle. In particular, the file's handle count is decremented. The `FileStream` object is given the specified buffer size. - - `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. Alternately, read and write to the handle before calling this `FileStream` constructor. - - `FileShare.Read` is the default for those constructors without a `FileShare` parameter. - + method will also close the handle. In particular, the file's handle count is decremented. The `FileStream` object is given the specified buffer size. + + `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. Alternately, read and write to the handle before calling this `FileStream` constructor. + + `FileShare.Read` is the default for those constructors without a `FileShare` parameter. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> is negative. - An I/O error, such as a disk error, occurred. - - -or- - + An I/O error, such as a disk error, occurred. + + -or- + The stream has been closed. The caller does not have the required permission. The requested is not permitted by the operating system for the specified file handle, such as when is or and the file handle is set for read-only access. @@ -988,6 +1010,7 @@ The file was too large (when @@ -1008,50 +1031,51 @@ The file was too large (when A bitwise combination of the enumeration values that determines how the file will be shared by processes. Initializes a new instance of the class with the specified path, creation mode, read/write permission, and sharing permission. - [!NOTE] -> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. - - is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . - +> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. + + is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - This code example is part of a larger example provided for the method. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + This code example is part of a larger example provided for the method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream3/CPP/fstreamlock.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/fstreamlock.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream3/VB/fstreamlock.vb" id="Snippet2"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/fstreamlock.fs" id="Snippet2"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream3/VB/fstreamlock.vb" id="Snippet2"::: + ]]> is . - .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. - - -or- - + .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. + + -or- + refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment. The file cannot be found, such as when is or , and the file specified by does not exist. The file must already exist in these modes. An I/O error, such as specifying when the file specified by already exists, occurred. - - -or- - + + -or- + The stream has been closed. The caller does not have the required permission. The specified path is invalid, such as being on an unmapped drive. @@ -1092,6 +1116,7 @@ The file was too large (when [System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")] [<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")>] - + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>] - + [System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")] [<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")>] @@ -1123,11 +1148,11 @@ The file was too large (when - - - - + + + + + A file handle for the file that this object will encapsulate. @@ -1139,29 +1164,29 @@ The file was too large (when if the handle was opened asynchronously (that is, in overlapped I/O mode); otherwise, . Initializes a new instance of the class for the specified file handle, with the specified read/write permission, instance ownership, buffer size, and synchronous or asynchronous state. - method will also close the handle. In particular, the file's handle count is decremented. The `FileStream` object is given the specified buffer size. - - `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. Alternately, read and write to the handle before calling this `FileStream` constructor. - - `FileShare.Read` is the default for those constructors without a `FileShare` parameter. - + method will also close the handle. In particular, the file's handle count is decremented. The `FileStream` object is given the specified buffer size. + + `FileStream` assumes that it has exclusive control over the handle. Reading, writing, or seeking while a `FileStream` is also holding a handle could result in data corruption. For data safety, call before using the handle, and avoid calling any methods other than `Close` after you are done using the handle. Alternately, read and write to the handle before calling this `FileStream` constructor. + + `FileShare.Read` is the default for those constructors without a `FileShare` parameter. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> is less than or greater than or is less than or equal to 0. The handle is invalid. - An I/O error, such as a disk error, occurred. - - -or- - + An I/O error, such as a disk error, occurred. + + -or- + The stream has been closed. The caller does not have the required permission. The requested is not permitted by the operating system for the specified file handle, such as when is or and the file handle is set for read-only access. @@ -1203,6 +1228,7 @@ The file was too large (when @@ -1225,45 +1251,45 @@ The file was too large (when A positive value greater than 0 indicating the buffer size. The default buffer size is 4096. Initializes a new instance of the class with the specified path, creation mode, read/write and sharing permission, and buffer size. - [!NOTE] -> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. - - is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . - +> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. + + is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> is . - .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. - - -or- - + .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. + + -or- + refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment. - is negative or zero. - - -or- - + is negative or zero. + + -or- + , , or contain an invalid value. The file cannot be found, such as when is or , and the file specified by does not exist. The file must already exist in these modes. An I/O error, such as specifying when the file specified by already exists, occurred. - - -or- - + + -or- + The stream has been closed. The caller does not have the required permission. The specified path is invalid, such as being on an unmapped drive. @@ -1307,6 +1333,7 @@ The file was too large (when @@ -1331,54 +1358,55 @@ The file was too large (when Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the underlying operating system might not support asynchronous I/O, so when specifying , the handle might be opened synchronously depending on the platform. When opened asynchronously, the and methods perform better on large reads or writes, but they might be much slower for small reads or writes. If the application is designed to take advantage of asynchronous I/O, set the parameter to . Using asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10. Initializes a new instance of the class with the specified path, creation mode, read/write and sharing permission, buffer size, and synchronous or asynchronous state. - [!NOTE] -> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. - - is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . - +> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. + + is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example shows how to asynchronously write data to a file and then verify that the data was written correctly. A `State` object is created to pass information from the main thread to the `EndReadCallback` and `EndWriteCallback` methods. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example shows how to asynchronously write data to a file and then verify that the data was written correctly. A `State` object is created to pass information from the main thread to the `EndReadCallback` and `EndWriteCallback` methods. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream2/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/source1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/source1.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet1"::: + ]]> is . - .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. - - -or- - + .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. + + -or- + refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment. - is negative or zero. - - -or- - + is negative or zero. + + -or- + , , or contain an invalid value. The file cannot be found, such as when is or , and the file specified by does not exist. The file must already exist in these modes. An I/O error, such as specifying when the file specified by already exists, occurred. - - -or- - + + -or- + The stream has been closed. The caller does not have the required permission. The specified path is invalid, such as being on an unmapped drive. @@ -1422,6 +1450,7 @@ The file was too large (when @@ -1430,12 +1459,12 @@ The file was too large (when - - - - - + + + + + + A relative or absolute path for the file that the current object will encapsulate. @@ -1446,63 +1475,64 @@ The file was too large (when A bitwise combination of the enumeration values that specifies additional file options. Initializes a new instance of the class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options. - object. - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. - + object. + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. + > [!NOTE] -> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. - - is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . - +> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. + + is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example writes data to a file and then reads the data using the object. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example writes data to a file and then reads the data using the object. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/IO.FileStream.ctor1/cpp/example.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/example.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IO.FileStream.ctor1/VB/example.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/example.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IO.FileStream.ctor1/VB/example.vb" id="Snippet1"::: + ]]> is . - .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. - - -or- - + .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. + + -or- + refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment. - is negative or zero. - - -or- - + is negative or zero. + + -or- + , , or contain an invalid value. The file cannot be found, such as when is or , and the file specified by does not exist. The file must already exist in these modes. - An I/O error, such as specifying when the file specified by already exists, occurred. - - -or- - + An I/O error, such as specifying when the file specified by already exists, occurred. + + -or- + The stream has been closed. The caller does not have the required permission. The specified path is invalid, such as being on an unmapped drive. - The requested is not permitted by the operating system for the specified , such as when is or and the file or directory is set for read-only access. - - -or- - + The requested is not permitted by the operating system for the specified , such as when is or and the file or directory is set for read-only access. + + -or- + is specified for , but file encryption is not supported on the current platform. The specified path, file name, or both exceed the system-defined maximum length. File and Stream I/O @@ -1556,57 +1586,57 @@ The file was too large (when A bitwise combination of the enumeration values that specifies additional file options. Initializes a new instance of the class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options. - constructor to apply access rights at the point of creation of a file. To access or modify rights on an existing file, consider using the and methods. - - The `fileOptions` parameter is used to provide access to more advanced operations that can be leveraged when creating a object. - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. - + constructor to apply access rights at the point of creation of a file. To access or modify rights on an existing file, consider using the and methods. + + The `fileOptions` parameter is used to provide access to more advanced operations that can be leveraged when creating a object. + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. + > [!NOTE] -> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. - - is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . - +> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. + + is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> is . - .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. - - -or- - + .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. + + -or- + refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment. - is negative or zero. - - -or- - + is negative or zero. + + -or- + , , or contain an invalid value. The file cannot be found, such as when is or , and the file specified by does not exist. The file must already exist in these modes. The current operating system is not Windows NT or later. - An I/O error, such as specifying when the file specified by already exists, occurred. - - -or- - + An I/O error, such as specifying when the file specified by already exists, occurred. + + -or- + The stream has been closed. The caller does not have the required permission. The specified path is invalid, such as being on an unmapped drive. - The requested is not permitted by the operating system for the specified , such as when is or and the file or directory is set for read-only access. - - -or- - + The requested is not permitted by the operating system for the specified , such as when is or and the file or directory is set for read-only access. + + -or- + is specified for , but file encryption is not supported on the current platform. The specified , file name, or both exceed the system-defined maximum length. File and Stream I/O @@ -1662,66 +1692,67 @@ The file was too large (when An object that determines the access control and audit security for the file. Initializes a new instance of the class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security. - constructor to apply access rights at the point of creation of a file. To access or modify rights on an existing file, consider using the and methods. - - The `fileOptions` parameter is used to provide access to more advanced operations that can be leveraged when creating a object. - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. - + constructor to apply access rights at the point of creation of a file. To access or modify rights on an existing file, consider using the and methods. + + The `fileOptions` parameter is used to provide access to more advanced operations that can be leveraged when creating a object. + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. + > [!NOTE] -> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. - - is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . - +> `path` is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device. + + is `true` for all objects that encapsulate files. If `path` indicates a device that does not support seeking, the property on the resulting is `false`. For additional information, see . + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + > [!IMPORTANT] > This constructor does not exist in .NET Core. Instead, starting in .NET Core 3.1, you can use the following extension method of the `FileSystemAclExtensions` class inside the `System.Security.AccessControl` assembly: . - -## Examples - The following example writes data to a file and then reads the data using the object. - + +## Examples + The following example writes data to a file and then reads the data using the object. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/IO.FileStream.ctor2/cpp/example.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileOptions/Overview/example.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IO.FileStream.ctor2/VB/example.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileOptions/Overview/example.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IO.FileStream.ctor2/VB/example.vb" id="Snippet1"::: + ]]> is . - .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. - - -or- - + .NET Framework and .NET Core versions older than 2.1: is an empty string (""), contains only white space, or contains one or more invalid characters. + + -or- + refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment. - is negative or zero. - - -or- - + is negative or zero. + + -or- + , , or contain an invalid value. The file cannot be found, such as when is or , and the file specified by does not exist. The file must already exist in these modes. - An I/O error, such as specifying when the file specified by already exists, occurred. - - -or- - + An I/O error, such as specifying when the file specified by already exists, occurred. + + -or- + The stream has been closed. The caller does not have the required permission. The specified path is invalid, such as being on an unmapped drive. - The requested is not permitted by the operating system for the specified , such as when is or and the file or directory is set for read-only access. - - -or- - + The requested is not permitted by the operating system for the specified , such as when is or and the file or directory is set for read-only access. + + -or- + is specified for , but file encryption is not supported on the current platform. The specified , file name, or both exceed the system-defined maximum length. The current operating system is not Windows NT or later. @@ -1737,11 +1768,11 @@ The file was too large (when - - - - - + + + + + @@ -1759,6 +1790,7 @@ The file was too large (when - - + + - - + + + + + [System.Runtime.CompilerServices.Nullable(2)] + [<System.Runtime.CompilerServices.Nullable(2)>] + + + - + + + + [System.Runtime.CompilerServices.Nullable(2)] + [<System.Runtime.CompilerServices.Nullable(2)>] + + + @@ -1823,11 +1869,11 @@ The file was too large (when - - - - - + + + + + @@ -1845,6 +1891,7 @@ The file was too large (when - - + + - - + + + + + [System.Runtime.CompilerServices.Nullable(2)] + [<System.Runtime.CompilerServices.Nullable(2)>] + + + - + + + + [System.Runtime.CompilerServices.Nullable(2)] + [<System.Runtime.CompilerServices.Nullable(2)>] + + + @@ -1938,6 +1999,7 @@ The file was too large (when if the stream supports reading; if the stream is closed or was opened with write-only access. - does not support reading, calls to the , , and methods throw a . - - If the stream is closed, this property returns `false`. - - - -## Examples - The following example demonstrates a use of the `CanRead` property. The output of this code is "MyFile.txt is not writable." To get the output message "MyFile.txt can be both written to and read from.", change the `FileAccess` parameter to `ReadWrite` in the `FileStream` constructor. - + does not support reading, calls to the , , and methods throw a . + + If the stream is closed, this property returns `false`. + + + +## Examples + The following example demonstrates a use of the `CanRead` property. The output of this code is "MyFile.txt is not writable." To get the output message "MyFile.txt can be both written to and read from.", change the `FileAccess` parameter to `ReadWrite` in the `FileStream` constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_Classic/classic FileStream.CanRead Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/CanRead/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic FileStream.CanRead Example/VB/source.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/CanRead/source.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic FileStream.CanRead Example/VB/source.vb" id="Snippet1"::: + ]]> File and Stream I/O @@ -2003,6 +2066,7 @@ The file was too large (when if the stream supports seeking; if the stream is closed or if the was constructed from an operating-system handle such as a pipe or output to the console. - does not support seeking, calls to , , , and throw a . - - If the stream is closed, this property returns `false`. - - - -## Examples - The following example uses the `CanSeek` property to check whether a stream supports seeking. - + does not support seeking, calls to , , , and throw a . + + If the stream is closed, this property returns `false`. + + + +## Examples + The following example uses the `CanSeek` property to check whether a stream supports seeking. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/FStream CanSeek/CPP/fstream canseek.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/CanSeek/fstream canseek.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/FStream CanSeek/VB/fstream canseek.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/CanSeek/fstream canseek.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/FStream CanSeek/VB/fstream canseek.vb" id="Snippet1"::: + ]]> File and Stream I/O @@ -2068,6 +2133,7 @@ The file was too large (when if the stream supports writing; if the stream is closed or was opened with read-only access. - does not support writing, a call to , , , or throws a . - - If the stream is closed, this property returns `false`. - - - -## Examples - The following example uses the `CanWrite` property to check whether a stream supports writing. - + does not support writing, a call to , , , or throws a . + + If the stream is closed, this property returns `false`. + + + +## Examples + The following example uses the `CanWrite` property to check whether a stream supports writing. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/FStream CanWrite/CPP/fstream canwrite.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/CanWrite/fstream canwrite.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/FStream CanWrite/VB/fstream canwrite.vb" id="Snippet1"::: - - The following is an example using the `CanWrite` property. The output of this code is "MyFile.txt is writable." To get the output message "MyFile.txt can be both written to and read from.", change the `FileAccess` parameter to `ReadWrite` in the `FileStream` constructor. - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/CanWrite/fstream canwrite.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/FStream CanWrite/VB/fstream canwrite.vb" id="Snippet1"::: + + The following is an example using the `CanWrite` property. The output of this code is "MyFile.txt is writable." To get the output message "MyFile.txt can be both written to and read from.", change the `FileAccess` parameter to `ReadWrite` in the `FileStream` constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_Classic/classic FileStream.CanWrite Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/CanWrite/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic FileStream.CanWrite Example/VB/source.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/CanWrite/source.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic FileStream.CanWrite Example/VB/source.vb" id="Snippet1"::: + ]]> File and Stream I/O @@ -2159,6 +2227,7 @@ See for more informat 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 mscorlib @@ -2174,9 +2243,9 @@ See for more informat System.Threading.Tasks.Task - - - + + + The stream to which the contents of the current file stream will be copied. @@ -2199,15 +2268,16 @@ For an example of copying between two streams, see the + The cancellation token was canceled. This exception is stored into the returned task. - - + + - - - + + + @@ -2239,6 +2309,7 @@ For an example of copying between two streams, see the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -2257,19 +2328,19 @@ For an example of copying between two streams, see the to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - + method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). File and Stream I/O @@ -2292,6 +2363,7 @@ For an example of copying between two streams, see the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 mscorlib @@ -2311,7 +2383,7 @@ For an example of copying between two streams, see the Asynchronously releases the unmanaged resources used by the . A task that represents the asynchronous dispose operation. - 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 System.IO.FileSystem @@ -2367,33 +2440,34 @@ Calling `DisposeAsync` allows the resources used by the System.Int32 - + The reference to the pending asynchronous request to wait for. Waits for the pending asynchronous read operation to complete. (Consider using instead.) The number of bytes read from the stream, between 0 and the number of bytes you requested. Streams only return 0 at the end of the stream, otherwise, they should block until at least 1 byte is available. - and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous file operations more easily. - - must be called exactly for every call to . Failing to end a read process before beginning another read can cause undesirable behavior such as deadlock. - - This method overrides . - - can be called on every from . Calling tells you how many bytes were read from the stream. will block until the I/O operation has completed. - - - -## Examples - This code example is part of a larger example provided for the constructor. - + and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous file operations more easily. + + must be called exactly for every call to . Failing to end a read process before beginning another read can cause undesirable behavior such as deadlock. + + This method overrides . + + can be called on every from . Calling tells you how many bytes were read from the stream. will block until the I/O operation has completed. + + + +## Examples + This code example is part of a larger example provided for the constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream2/CPP/source.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/source1.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet4"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/source1.fs" id="Snippet4"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet4"::: + ]]> @@ -2436,6 +2510,7 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 System.IO.FileSystem @@ -2450,30 +2525,31 @@ Calling `DisposeAsync` allows the resources used by the System.Void - + The pending asynchronous I/O request. Ends an asynchronous write operation and blocks until the I/O operation is complete. (Consider using instead.) - and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous file operations more easily. - - This method overrides . - - must be called exactly once on every from . will block until the I/O operation has completed. - - - -## Examples - This code example is part of a larger example provided for the constructor. - + and to implement asynchronous file operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous file operations more easily. + + This method overrides . + + must be called exactly once on every from . will block until the I/O operation has completed. + + + +## Examples + This code example is part of a larger example provided for the constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream2/CPP/source.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/source1.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet3"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/source1.fs" id="Snippet3"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet3"::: + ]]> @@ -2521,6 +2597,7 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -2535,11 +2612,11 @@ Calling `DisposeAsync` allows the resources used by the Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the . - File and Stream I/O @@ -2589,6 +2666,7 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -2603,32 +2681,33 @@ Calling `DisposeAsync` allows the resources used by the Clears buffers for this stream and causes any buffered data to be written to the file. - . - - When you call the method, the operating system I/O buffer is also flushed. - - A stream's encoder is not flushed unless you explicitly call or dispose of the object. Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. - - Because a buffer can be used for either reading or writing, performs the following two functions: - -- Any data previously written to the buffer is copied to the file and the buffer is cleared except for its encoder state. - -- If is `true` and data was previously copied from the file to the buffer for reading, the current position within the file is decremented by the number of unread bytes in the buffer. The buffer is then cleared. - - Use the method overload when you want to ensure that all buffered data in intermediate file buffers is written to disk. - - - -## Examples - This code example is part of a larger example provided for the method. - + . + + When you call the method, the operating system I/O buffer is also flushed. + + A stream's encoder is not flushed unless you explicitly call or dispose of the object. Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. + + Because a buffer can be used for either reading or writing, performs the following two functions: + +- Any data previously written to the buffer is copied to the file and the buffer is cleared except for its encoder state. + +- If is `true` and data was previously copied from the file to the buffer for reading, the current position within the file is decremented by the number of unread bytes in the buffer. The buffer is then cleared. + + Use the method overload when you want to ensure that all buffered data in intermediate file buffers is written to disk. + + + +## Examples + This code example is part of a larger example provided for the method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream3/CPP/fstreamlock.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/fstreamlock.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream3/VB/fstreamlock.vb" id="Snippet4"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/fstreamlock.fs" id="Snippet4"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream3/VB/fstreamlock.vb" id="Snippet4"::: + ]]> An I/O error occurred. @@ -2668,6 +2747,7 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -2679,20 +2759,20 @@ Calling `DisposeAsync` allows the resources used by the System.Void - + to flush all intermediate file buffers; otherwise, . Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers. - method, the operating system I/O buffer is also flushed. - + method, the operating system I/O buffer is also flushed. + ]]> @@ -2729,6 +2809,7 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -2744,23 +2825,24 @@ Calling `DisposeAsync` allows the resources used by the System.Threading.Tasks.Task - + The token to monitor for cancellation requests. Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. A task that represents the asynchronous flush operation. - value for the property. If the handle to the file is disposed, the returned task contains the exception in the property. - + value for the property. If the handle to the file is disposed, the returned task contains the exception in the property. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> The stream has been disposed. + The cancellation token was canceled. This exception is stored into the returned task. Cancellation @@ -2801,24 +2883,24 @@ Calling `DisposeAsync` allows the resources used by the Gets a object that encapsulates the access control list (ACL) entries for the file described by the current object. An object that encapsulates the access control settings for the file described by the current object. - class and can be used to retrieve the access control list (ACL) entries of an existing file, consider using method, as it is easier to use. - - Use the method to retrieve the ACL entries for a file. - - An ACL describes individuals and/or groups who have, or do not have, rights to specific actions on the given file. For more information, see [How to: Add or Remove Access Control List Entries](/dotnet/standard/io/how-to-add-or-remove-access-control-list-entries). - + class and can be used to retrieve the access control list (ACL) entries of an existing file, consider using method, as it is easier to use. + + Use the method to retrieve the ACL entries for a file. + + An ACL describes individuals and/or groups who have, or do not have, rights to specific actions on the given file. For more information, see [How to: Add or Remove Access Control List Entries](/dotnet/standard/io/how-to-add-or-remove-access-control-list-entries). + ]]> The file is closed. An I/O error occurred while opening the file. The file could not be found. - This operation is not supported on the current platform. - - -or- - + This operation is not supported on the current platform. + + -or- + The caller does not have the required permission. @@ -2850,6 +2932,7 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 System.IO.FileSystem @@ -2859,7 +2942,7 @@ Calling `DisposeAsync` allows the resources used by the [System.Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. https://go.microsoft.com/fwlink/?linkid=14202")] [<System.Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. https://go.microsoft.com/fwlink/?linkid=14202")>] - + [System.Obsolete("FileStream.Handle has been deprecated. Use FileStream's SafeFileHandle property instead.")] [<System.Obsolete("FileStream.Handle has been deprecated. Use FileStream's SafeFileHandle property instead.")>] @@ -2883,16 +2966,16 @@ Calling `DisposeAsync` allows the resources used by the Gets the operating system file handle for the file that the current object encapsulates. The operating system file handle for the file encapsulated by this object, or -1 if the has been closed. - property to discover whether this handle was opened asynchronously. In Win32, this means the handle was opened for overlapped IO, and it requires different parameters to `ReadFile` and `WriteFile`. - + property to discover whether this handle was opened asynchronously. In Win32, this means the handle was opened for overlapped IO, and it requires different parameters to `ReadFile` and `WriteFile`. + > [!CAUTION] -> Data corruption might occur if a `FileStream` is created, its handle is passed, some operation moves the handle's file pointer, and then the `FileStream` is used again. Multiple threads cannot safely write to the same file simultaneously, and `FileStream` buffering code assumes that it exclusively controls the handle. `FileStream` might throw an if `FileStream` detects that some other process has moved the file pointer. To avoid this, do not write any data into a portion of the file that `FileStream` might have buffered, and restore the file pointer to the location it had when methods were last called on `FileStream`. - +> Data corruption might occur if a `FileStream` is created, its handle is passed, some operation moves the handle's file pointer, and then the `FileStream` is used again. Multiple threads cannot safely write to the same file simultaneously, and `FileStream` buffering code assumes that it exclusively controls the handle. `FileStream` might throw an if `FileStream` detects that some other process has moved the file pointer. To avoid this, do not write any data into a portion of the file that `FileStream` might have buffered, and restore the file pointer to the location it had when methods were last called on `FileStream`. + ]]> The caller does not have the required permission. @@ -2934,6 +3017,7 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 System.Boolean @@ -2943,22 +3027,23 @@ Calling `DisposeAsync` allows the resources used by the if the was opened asynchronously; otherwise, . - property correctly. In Win32, `IsAsync` being true means the handle was opened for overlapped I/O, and thus requires different parameters to `ReadFile` and `WriteFile`. - - You specify this value when you create an instance of the class using a constructor that has an `isAsync`, `useAsync`, or `options` parameter. When the property is `true`, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the property does not have to be `true` to call the , , or method. When the property is `false` and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously. - - - -## Examples - This code example is part of a larger example provided for the constructor. - + property correctly. In Win32, `IsAsync` being true means the handle was opened for overlapped I/O, and thus requires different parameters to `ReadFile` and `WriteFile`. + + You specify this value when you create an instance of the class using a constructor that has an `isAsync`, `useAsync`, or `options` parameter. When the property is `true`, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the property does not have to be `true` to call the , , or method. When the property is `false` and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously. + + + +## Examples + This code example is part of a larger example provided for the constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream2/CPP/source.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/source1.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet2"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/source1.fs" id="Snippet2"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet2"::: + ]]> File and Stream I/O @@ -2999,6 +3084,7 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -3013,20 +3099,21 @@ Calling `DisposeAsync` allows the resources used by the Gets the length in bytes of the stream. A long value representing the length of the stream in bytes. - @@ -3065,24 +3152,25 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 System.IO.FileSystem - + [System.Runtime.Versioning.UnsupportedOSPlatform("ios")] [<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("macos")] [<System.Runtime.Versioning.UnsupportedOSPlatform("macos")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("tvos")] [<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("freebsd")] [<System.Runtime.Versioning.UnsupportedOSPlatform("freebsd")>] @@ -3095,30 +3183,31 @@ Calling `DisposeAsync` allows the resources used by the System.Void - - + + The beginning of the range to lock. The value of this parameter must be equal to or greater than zero (0). The range to be locked. Prevents other processes from reading from or writing to the . - @@ -3137,9 +3226,9 @@ Calling `DisposeAsync` allows the resources used by the - - - + + + Property System.IO.FileSystem @@ -3166,6 +3255,7 @@ Calling `DisposeAsync` allows the resources used by the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -3180,23 +3270,24 @@ Calling `DisposeAsync` allows the resources used by the Gets the absolute path of the file opened in the . A string that is the absolute path of the file. - constructor. - + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + This code example is part of a larger example provided for the constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream2/CPP/source.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/source1.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet4"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/source1.fs" id="Snippet4"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream2/VB/source.vb" id="Snippet4"::: + ]]> File and Stream I/O @@ -3237,6 +3328,7 @@ If the absolute path is not known, this property returns a string similar to "[U 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -3255,20 +3347,21 @@ If the absolute path is not known, this property returns a string similar to "[U Gets or sets the current position of this stream. The current position of this stream. - The stream does not support seeking. @@ -3295,6 +3388,7 @@ If the absolute path is not known, this property returns a string similar to "[U 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 mscorlib @@ -3306,11 +3400,17 @@ If the absolute path is not known, this property returns a string similar to "[U System.IO.FileSystem + + + [System.Runtime.CompilerServices.NullableContext(0)] + [<System.Runtime.CompilerServices.NullableContext(0)>] + + System.Int32 - + A region of memory. When this method returns, the contents of this region are replaced by the bytes read from the current file stream. @@ -3338,11 +3438,11 @@ Use for reading primitive data types. - - - - - + + + + + Method @@ -3370,6 +3470,7 @@ Use for reading primitive data types. 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -3382,7 +3483,7 @@ Use for reading primitive data types. - + @@ -3394,29 +3495,30 @@ Use for reading primitive data types. Reads a block of bytes from the stream and writes the data in a given buffer. The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached. - . - - The `offset` parameter gives the offset of the byte in `array` (the buffer index) at which to begin reading, and the `count` parameter gives the maximum number of bytes to be read from this stream. The returned value is the actual number of bytes read, or zero if the end of the stream is reached. If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged. - - The method returns zero only after reaching the end of the stream. Otherwise, always reads at least one byte from the stream before returning. If no data is available from the stream upon a call to , the method will block until at least one byte of data can be returned. An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. - - Use for reading primitive data types. - - Do not interrupt a thread that is performing a read operation. Although the application may appear to run successfully after the thread is unblocked, the interruption can decrease your application's performance and reliability. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example reads the contents from a and writes it into another . - + . + + The `offset` parameter gives the offset of the byte in `array` (the buffer index) at which to begin reading, and the `count` parameter gives the maximum number of bytes to be read from this stream. The returned value is the actual number of bytes read, or zero if the end of the stream is reached. If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged. + + The method returns zero only after reaching the end of the stream. Otherwise, always reads at least one byte from the stream before returning. If no data is available from the stream upon a call to , the method will block until at least one byte of data can be returned. An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. + + Use for reading primitive data types. + + Do not interrupt a thread that is performing a read operation. Although the application may appear to run successfully after the thread is unblocked, the interruption can decrease your application's performance and reliability. + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example reads the contents from a and writes it into another . + :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/Read/fsread.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/FSRead/VB/fsread.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/Read/fsread.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/FSRead/VB/fsread.vb" id="Snippet1"::: + ]]> @@ -3447,6 +3549,7 @@ Use for reading primitive data types. 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 mscorlib @@ -3458,18 +3561,24 @@ Use for reading primitive data types. System.IO.FileSystem + + + [System.Runtime.CompilerServices.NullableContext(0)] + [<System.Runtime.CompilerServices.NullableContext(0)>] + + System.Threading.Tasks.ValueTask<System.Int32> - - + + The buffer to write the data into. The token to monitor for cancellation requests. The default value is . Asynchronously reads a sequence of bytes from the current file stream and writes them to a memory region, advances the position within the file stream by the number of bytes read, and monitors cancellation requests. - A task that represents the asynchronous read operation and wraps the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. + A task that, when awaited, returns the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3523,6 +3634,7 @@ The following example shows how to read from a file asynchronously. 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -3538,10 +3650,10 @@ The following example shows how to read from a file asynchronously. System.Threading.Tasks.Task<System.Int32> - - - - + + + + The buffer to write the data into. @@ -3549,7 +3661,7 @@ The following example shows how to read from a file asynchronously. The maximum number of bytes to read. The token to monitor for cancellation requests. Asynchronously reads a sequence of bytes from the current file stream and writes them to a byte array beginning at a specified offset, advances the position within the file stream by the number of bytes read, and monitors cancellation requests. - A task that represents the asynchronous read operation and wraps the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. + A task that, when awaited, returns the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. @@ -3580,6 +3693,7 @@ The following example shows how to read from a file asynchronously. The stream does not support reading. The stream has been disposed. The stream is currently in use by a previous read operation. + The cancellation token was canceled. This exception is stored into the returned task. Cancellation @@ -3616,6 +3730,7 @@ The following example shows how to read from a file asynchronously. 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -3631,30 +3746,31 @@ The following example shows how to read from a file asynchronously. Reads a byte from the file and advances the read position one byte. The byte, cast to an , or -1 if the end of the stream has been reached. - . - + . + > [!NOTE] -> Use the property to determine whether the current instance supports reading. For additional information, see . - - - -## Examples - The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly. - +> Use the property to determine whether the current instance supports reading. For additional information, see . + + + +## Examples + The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream1/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream1/VB/source.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/source.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream1/VB/source.vb" id="Snippet1"::: + ]]> The current stream does not support reading. The current stream is closed. - The default implementation on creates a new single-byte array and then calls . While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call. - + The default implementation on creates a new single-byte array and then calls . While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call. + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). File and Stream I/O @@ -3694,6 +3810,7 @@ The following example shows how to read from a file asynchronously. 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -3708,11 +3825,11 @@ The following example shows how to read from a file asynchronously. Gets a object that represents the operating system file handle for the file that the current object encapsulates. An object that represents the operating system file handle for the file that the current object encapsulates. - property automatically flushes the stream and sets the current stream position to 0. This allows the file to be moved or the stream position to be reset by another stream using the returned by this property. - + property automatically flushes the stream and sets the current stream position to 0. This allows the file to be moved or the stream position to be reset by another stream using the returned by this property. + ]]> File and Stream I/O @@ -3753,6 +3870,7 @@ The following example shows how to read from a file asynchronously. 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -3773,30 +3891,32 @@ The following example shows how to read from a file asynchronously. Sets the current position of this stream to the given value. The new position in the stream. - . - + . + > [!NOTE] -> Use the property to determine whether the current instance supports seeking. For additional information, see . - +> Use the property to determine whether the current instance supports seeking. For additional information, see . + You can seek to any location beyond the length of the stream. When you seek beyond the length of the file, the file size grows. Data added to the end of the file is set to zero. - + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - -## Examples - The following example shows how to write data to a file, byte by byte, and then verify that the data was written correctly. - + +## Examples + The following example shows how to write data to a file, byte by byte, and then verify that the data was written correctly. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream1/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream1/VB/source.vb" id="Snippet1"::: - - The following example reads text in the reverse direction, from the end of file to the beginning of the file, by using the various values with the method. - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/source.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream1/VB/source.vb" id="Snippet1"::: + + The following example reads text in the reverse direction, from the end of file to the beginning of the file, by using the various values with the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/Seek/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.filestream.seek/vb/source.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/Seek/source.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.filestream.seek/vb/source.vb" id="Snippet1"::: + ]]> An I/O error occurred. @@ -3847,18 +3967,18 @@ The following example shows how to read from a file asynchronously. An object that describes an ACL entry to apply to the current file. Applies access control list (ACL) entries described by a object to the file described by the current object. - class and can be used on an existing file, consider using the method as it is easier to use. - - The method applies access control list (ACL) entries to a file that represents the noninherited ACL list. - + class and can be used on an existing file, consider using the method as it is easier to use. + + The method applies access control list (ACL) entries to a file that represents the noninherited ACL list. + > [!CAUTION] -> The ACL specified for the `fileSecurity` parameter replaces the existing ACL for the file. To add permissions for a new user, use the method to obtain the existing ACL, modify it, and then use to apply it back to the file. - - An ACL describes individuals and/or groups who have, or do not have, rights to specific actions on the given file. For more information, see [How to: Add or Remove Access Control List Entries](/dotnet/standard/io/how-to-add-or-remove-access-control-list-entries). - +> The ACL specified for the `fileSecurity` parameter replaces the existing ACL for the file. To add permissions for a new user, use the method to obtain the existing ACL, modify it, and then use to apply it back to the file. + + An ACL describes individuals and/or groups who have, or do not have, rights to specific actions on the given file. For more information, see [How to: Add or Remove Access Control List Entries](/dotnet/standard/io/how-to-add-or-remove-access-control-list-entries). + ]]> The file is closed. @@ -3900,6 +4020,7 @@ The following example shows how to read from a file asynchronously. 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -3917,20 +4038,20 @@ The following example shows how to read from a file asynchronously. The new length of the stream. Sets the length of this stream to the given value. - . - - If the given value is less than the current length of the stream, the stream is truncated. In this scenario, if the current position is greater than the new length, the current position is moved to the last byte of the stream. If the given value is larger than the current length of the stream, the stream is expanded, and the current position remains the same. If the stream is expanded, the contents of the stream between the old and the new length are undefined on Windows, while on Linux, that space is filled with zeros. - - A stream must support both writing and seeking for `SetLength` to work. - + . + + If the given value is less than the current length of the stream, the stream is truncated. In this scenario, if the current position is greater than the new length, the current position is moved to the last byte of the stream. If the given value is larger than the current length of the stream, the stream is expanded, and the current position remains the same. If the stream is expanded, the contents of the stream between the old and the new length are undefined on Windows, while on Linux, that space is filled with zeros. + + A stream must support both writing and seeking for `SetLength` to work. + > [!NOTE] -> Use the property to determine whether the current instance supports writing, and the property to determine whether seeking is supported. For additional information, see and . - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - +> Use the property to determine whether the current instance supports writing, and the property to determine whether seeking is supported. For additional information, see and . + + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> An I/O error has occurred. @@ -3969,24 +4090,25 @@ The following example shows how to read from a file asynchronously. 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 System.IO.FileSystem - + [System.Runtime.Versioning.UnsupportedOSPlatform("ios")] [<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("macos")] [<System.Runtime.Versioning.UnsupportedOSPlatform("macos")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("tvos")] [<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>] - + [System.Runtime.Versioning.UnsupportedOSPlatform("freebsd")] [<System.Runtime.Versioning.UnsupportedOSPlatform("freebsd")>] @@ -3999,28 +4121,29 @@ The following example shows how to read from a file asynchronously. System.Void - - + + The beginning of the range to unlock. The range to be unlocked. Allows access by other processes to all or part of a file that was previously locked. - @@ -4045,6 +4168,7 @@ The following example shows how to read from a file asynchronously. 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 mscorlib @@ -4056,11 +4180,17 @@ The following example shows how to read from a file asynchronously. System.IO.FileSystem + + + [System.Runtime.CompilerServices.NullableContext(0)] + [<System.Runtime.CompilerServices.NullableContext(0)>] + + System.Void - + A region of memory. This method copies the contents of this region to the current file stream. @@ -4076,6 +4206,7 @@ If the write operation is successful, the position within the file stream advanc ]]> + .NET 8 and later versions: The underlying pipe is closed or disconnected. @@ -4085,11 +4216,11 @@ If the write operation is successful, the position within the file stream advanc - - - - - + + + + + Method System.IO.FileSystem @@ -4116,6 +4247,7 @@ If the write operation is successful, the position within the file stream advanc 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -4128,7 +4260,7 @@ If the write operation is successful, the position within the file stream advanc - + @@ -4139,29 +4271,29 @@ If the write operation is successful, the position within the file stream advanc The maximum number of bytes to write. Writes a block of bytes to the file stream. - . - - The `offset` parameter gives the offset of the byte in `array` (the buffer index) at which to begin copying, and the `count` parameter gives the number of bytes that will be written to the stream. If the write operation is successful, the current position of the stream is advanced by the number of bytes written. If an exception occurs, the current position of the stream is unchanged. - + . + +The `offset` parameter gives the offset of the byte in `array` (the buffer index) at which to begin copying, and the `count` parameter gives the number of bytes that will be written to the stream. If the write operation is successful, the current position of the stream is advanced by the number of bytes written. If an exception occurs, the current position of the stream is unchanged. + > [!NOTE] -> Use the property to determine whether the current instance supports writing. For additional information, see . - - Do not interrupt a thread that is performing a write operation. Although the application may appear to run successfully after the thread is unblocked, the interruption can decrease your application's performance and reliability. - - For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - This code example is part of a larger example provided for the method. - +> Use the property to determine whether the current instance supports writing. For additional information, see . + +Do not interrupt a thread that's performing a write operation. Although the application may appear to run successfully after the thread is unblocked, the interruption can decrease your application's performance and reliability. + +For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + +## Examples + This code example is part of a larger example provided for the method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream3/CPP/fstreamlock.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/fstreamlock.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream3/VB/fstreamlock.vb" id="Snippet3"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/fstreamlock.fs" id="Snippet3"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream3/VB/fstreamlock.vb" id="Snippet3"::: + ]]> @@ -4170,16 +4302,20 @@ If the write operation is successful, the position within the file stream advanc and describe an invalid range in . or is negative. - An I/O error occurred. - + An I/O error occurred. + +-or- + +Another thread may have caused an unexpected change in the position of the operating system's file handle. + -or- - - Another thread may have caused an unexpected change in the position of the operating system's file handle. + +.NET 8 and later versions: The underlying pipe is closed or disconnected. The stream is closed. The current stream instance does not support writing. - File and Stream I/O - How to: Read Text from a File - How to: Write Text to a File + File and stream I/O + How to: Read text from a file + How to: Write text to a file @@ -4196,6 +4332,7 @@ If the write operation is successful, the position within the file stream advanc 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 mscorlib @@ -4207,12 +4344,18 @@ If the write operation is successful, the position within the file stream advanc System.IO.FileSystem + + + [System.Runtime.CompilerServices.NullableContext(0)] + [<System.Runtime.CompilerServices.NullableContext(0)>] + + System.Threading.Tasks.ValueTask - - + + The region of memory to write data from. @@ -4224,7 +4367,7 @@ If the write operation is successful, the position within the file stream advanc ## Remarks -The `WriteAsync` method lets you perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. +The `WriteAsync` method lets you perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in apps where a time-consuming stream operation can block the UI thread and make your app appear as if it isn't working. Use the property to determine whether the current instance supports writing. @@ -4232,6 +4375,7 @@ If the operation is canceled before it completes, the returned task contains the ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -4265,6 +4409,7 @@ If the operation is canceled before it completes, the returned task contains the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -4280,10 +4425,10 @@ If the operation is canceled before it completes, the returned task contains the System.Threading.Tasks.Task - - - - + + + + The buffer to write data from. @@ -4293,24 +4438,22 @@ If the operation is canceled before it completes, the returned task contains the Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. - method enables you to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - Use the property to determine whether the current instance supports writing. - - If the operation is canceled before it completes, the returned task contains the value for the property. If the handle to the file is disposed, the returned task contains the exception in the property. - - - -## Examples - The following example shows how to write asynchronously to a file. - + method enables you to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in apps where a time-consuming stream operation can block the UI thread and make your app appear as if it isn't working. + + Use the property to determine whether the current instance supports writing. + + If the operation is canceled before it completes, the returned task contains the value for the property. If the handle to the file is disposed, the returned task contains the exception in the property. + +This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + +## Examples + The following example shows how to write asynchronously to a file. + :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/Overview/example3.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Asynchronous_File_IO_async/vb/example3.vb" id="Snippet3"::: - - This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Asynchronous_File_IO_async/vb/example3.vb" id="Snippet3"::: ]]> @@ -4319,10 +4462,11 @@ If the operation is canceled before it completes, the returned task contains the or is negative. The sum of and is larger than the buffer length. + Cancellation The stream does not support writing. The stream has been disposed. The stream is currently in use by a previous write operation. - Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -4358,6 +4502,7 @@ If the operation is canceled before it completes, the returned task contains the 5.0.0.0 6.0.0.0 7.0.0.0 + 8.0.0.0 @@ -4375,32 +4520,32 @@ If the operation is canceled before it completes, the returned task contains the A byte to write to the stream. Writes a byte to the current position in the file stream. - . - - Use `WriteByte` to write a byte to a `FileStream` efficiently. If the stream is closed or not writable, an exception will be thrown. - + . + + Use `WriteByte` to write a byte to a `FileStream` efficiently. If the stream is closed or not writable, an exception will be thrown. + > [!NOTE] -> Use the property to determine whether the current instance supports writing. For additional information, see . - - - -## Examples - The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly. - +> Use the property to determine whether the current instance supports writing. For additional information, see . + +## Examples + The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.FileStream1/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/.ctor/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream1/VB/source.vb" id="Snippet1"::: - + :::code language="fsharp" source="~/snippets/fsharp/System.IO/FileStream/.ctor/source.fs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.FileStream1/VB/source.vb" id="Snippet1"::: + ]]> The stream is closed. The stream does not support writing. + .NET 8 and later versions: The underlying pipe is closed or disconnected. - The default implementation on creates a new single-byte array and then calls . While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call. - + The default implementation on creates a new single-byte array and then calls . While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call. + For a list of common file and directory operations, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). File and Stream I/O diff --git a/xml/System.IO/MemoryStream.xml b/xml/System.IO/MemoryStream.xml index 50ecf0e9ace..3e9cab302a9 100644 --- a/xml/System.IO/MemoryStream.xml +++ b/xml/System.IO/MemoryStream.xml @@ -68,28 +68,28 @@ Creates a stream whose backing store is memory. - method. When a new instance of is created, the current position is set to zero. - + method. When a new instance of is created, the current position is set to zero. + [!INCLUDE[note_unnecessary_dispose](~/includes/note-unnecessary-dispose.md)] - - Memory streams created with an unsigned byte array provide a non-resizable stream of the data. When using a byte array, you can neither append to nor shrink the stream, although you might be able to modify the existing contents depending on the parameters passed into the constructor. Empty memory streams are resizable, and can be written to and read from. - - If a object is added to a ResX file or a .resources file, call the method at runtime to retrieve it. - - If a object is serialized to a resource file it will actually be serialized as an . This behavior provides better performance, as well as the ability to get a pointer to the data directly, without having to go through methods. - - - -## Examples - The following code example shows how to read and write data using memory as a backing store. - + + Memory streams created with an unsigned byte array provide a non-resizable stream of the data. When using a byte array, you can neither append to nor shrink the stream, although you might be able to modify the existing contents depending on the parameters passed into the constructor. Empty memory streams are resizable, and can be written to and read from. + + If a object is added to a ResX file or a .resources file, call the method at runtime to retrieve it. + + If a object is serialized to a resource file it will actually be serialized as an . This behavior provides better performance, as well as the ability to get a pointer to the data directly, without having to go through methods. + + + +## Examples + The following code example shows how to read and write data using memory as a backing store. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet1"::: + ]]> File and Stream I/O @@ -149,15 +149,15 @@ Initializes a new instance of the class with an expandable capacity initialized to zero. - , , and properties are all set to `true`. - - The capacity of the current stream automatically increases when you use the method to set the length to a value larger than the capacity of the current stream. - - This constructor exposes the underlying stream, which returns. - + , , and properties are all set to `true`. + + The capacity of the current stream automatically increases when you use the method to set the length to a value larger than the capacity of the current stream. + + This constructor exposes the underlying stream, which returns. + ]]> File and Stream I/O @@ -216,15 +216,15 @@ The array of unsigned bytes from which to create the current stream. Initializes a new non-resizable instance of the class based on the specified byte array. - , , and properties are all set to `true`. is set to the length of the specified byte array. The new stream can be written to, but is not resizable. - - The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). - - This constructor does not expose the underlying stream. throws . - + , , and properties are all set to `true`. is set to the length of the specified byte array. The new stream can be written to, but is not resizable. + + The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). + + This constructor does not expose the underlying stream. throws . + ]]> @@ -279,24 +279,24 @@ The initial size of the internal array in bytes. Initializes a new instance of the class with an expandable capacity initialized as specified. - , , and properties are all set to `true`. - - The capacity automatically increases when you use the method to set the length to a value larger than the capacity of the current stream. Except for a `MemoryStream` constructed with a byte[] parameter, write operations at the end of a `MemoryStream` expand the `MemoryStream`. - - This constructor exposes the underlying stream that returns. - - - -## Examples - This code example is part of a larger example provided for the class. - + , , and properties are all set to `true`. + + The capacity automatically increases when you use the method to set the length to a value larger than the capacity of the current stream. Except for a `MemoryStream` constructed with a byte[] parameter, write operations at the end of a `MemoryStream` expand the `MemoryStream`. + + This constructor exposes the underlying stream that returns. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet2"::: + ]]> @@ -353,15 +353,15 @@ The setting of the property, which determines whether the stream supports writing. Initializes a new non-resizable instance of the class based on the specified byte array with the property set as specified. - and properties are both set to `true`. is set to the length of the specified byte array. - - The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). - - This constructor does not expose the underlying stream. throws . - + and properties are both set to `true`. is set to the length of the specified byte array. + + The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). + + This constructor does not expose the underlying stream. throws . + ]]> @@ -420,15 +420,15 @@ The length of the stream in bytes. Initializes a new non-resizable instance of the class based on the specified region (index) of a byte array. - , , and properties are all set to `true`, but the capacity cannot be changed. is set to `count`. - - The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). - - This constructor does not expose the underlying stream. throws . However, you can write to the stream. - + , , and properties are all set to `true`, but the capacity cannot be changed. is set to `count`. + + The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). + + This constructor does not expose the underlying stream. throws . However, you can write to the stream. + ]]> @@ -492,15 +492,15 @@ The setting of the property, which determines whether the stream supports writing. Initializes a new non-resizable instance of the class based on the specified region of a byte array, with the property set as specified. - and properties are both set to `true`. is set to `count`. - - The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). - - This constructor does not expose the underlying stream. throws . However, you can write to the stream if `writable` is `true`. - + and properties are both set to `true`. is set to `count`. + + The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). + + This constructor does not expose the underlying stream. throws . However, you can write to the stream if `writable` is `true`. + ]]> @@ -566,13 +566,13 @@ to enable , which returns the unsigned byte array from which the stream was created; otherwise, . Initializes a new instance of the class based on the specified region of a byte array, with the property set as specified, and the ability to call set as specified. - and properties are both set to `true`. is set to `count`. - - The new stream instance can be written to, but the of the underlying byte array cannot be changed. The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). - + and properties are both set to `true`. is set to `count`. + + The new stream instance can be written to, but the of the underlying byte array cannot be changed. The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see ). + ]]> @@ -761,13 +761,13 @@ Refer to the remarks for additional usage if the stream is open. - does not support reading, calls to the and methods throw a . - - If the stream is closed, this property returns `false`. - + does not support reading, calls to the and methods throw a . + + If the stream is closed, this property returns `false`. + ]]> File and Stream I/O @@ -821,13 +821,13 @@ Refer to the remarks for additional usage if the stream is open. - does not support seeking, calls to , , , and throw a . - - If the stream is closed, this property returns `false`. - + does not support seeking, calls to , , , and throw a . + + If the stream is closed, this property returns `false`. + ]]> File and Stream I/O @@ -881,13 +881,13 @@ Refer to the remarks for additional usage if the stream supports writing; otherwise, . - does not support writing, a call to , , or throws a . - - If the stream is closed, this property returns `false`. - + does not support writing, a call to , , or throws a . + + If the stream is closed, this property returns `false`. + ]]> File and Stream I/O @@ -946,20 +946,20 @@ Refer to the remarks for additional usage Gets or sets the number of bytes allocated for this stream. The length of the usable portion of the buffer for the stream. - class. - + class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet5"::: + ]]> A capacity is set that is negative or less than the current length of the stream. @@ -1004,7 +1004,7 @@ Refer to the remarks for additional usage . The buffer is still available on a once the stream has been closed. @@ -1013,7 +1013,7 @@ Flushing the stream will not flush its underlying encoder unless you explicitly Attempting to manipulate a stream after it has been closed might throw an . -## Examples +## Examples This code example is part of a larger example provided for the class. ```vb @@ -1139,6 +1139,7 @@ The stream is unwritable. is negative or zero. Either the current stream or the destination stream is disposed. The current stream does not support reading, or the destination stream does not support writing. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1189,19 +1190,19 @@ The stream is unwritable. to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the class and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. - + method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). @@ -1372,13 +1373,13 @@ The pending operation does not support writing. Overrides the method so that no action is performed. - method. - - Because any data written to a object is written into RAM, this method is redundant. - + method. + + Because any data written to a object is written into RAM, this method is redundant. + ]]> File and Stream I/O @@ -1439,21 +1440,22 @@ The pending operation does not support writing. Asynchronously clears all buffers for this stream, and monitors cancellation requests. A task that represents the asynchronous flush operation. - object is written into RAM, this method is redundant. - - If the operation is canceled before it completes, the returned task contains the value for the property. - - You can create a cancellation token by creating an instance of the class and passing the property as the `cancellationToken` parameter. - + object is written into RAM, this method is redundant. + + If the operation is canceled before it completes, the returned task contains the value for the property. + + You can create a cancellation token by creating an instance of the class and passing the property as the `cancellationToken` parameter. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> The stream has been disposed. Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1505,18 +1507,18 @@ The pending operation does not support writing. Returns the array of unsigned bytes from which this stream was created. The byte array from which this stream was created, or the underlying array if a byte array was not provided to the constructor during construction of the current instance. - object, the length of the buffer returned from is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the method; however, creates a copy of the data in memory. - - The buffer can also be `null`. - - To create a `MemoryStream` instance with a publicly visible buffer, use , , or . If the current stream is resizable, two calls to this method do not return the same array if the underlying byte array is resized between calls. For additional information, see . - + object, the length of the buffer returned from is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the method; however, creates a copy of the data in memory. + + The buffer can also be `null`. + + To create a `MemoryStream` instance with a publicly visible buffer, use , , or . If the current stream is resizable, two calls to this method do not return the same array if the underlying byte array is resized between calls. For additional information, see . + > [!NOTE] -> This method works when the memory stream is closed. - +> This method works when the memory stream is closed. + ]]> The instance was not created with a publicly visible buffer. @@ -1576,15 +1578,15 @@ The pending operation does not support writing. Gets the length of the stream in bytes. The length of the stream in bytes. - class. - + class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet5"::: + ]]> The stream is closed. @@ -1678,15 +1680,15 @@ The pending operation does not support writing. Gets or sets the current position within the stream. The current position within the stream. - class. - + class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet5"::: + ]]> The position is set to a negative value or a value greater than Int32.MaxValue. @@ -1805,31 +1807,31 @@ The pending operation does not support writing. Reads a block of bytes from the current stream and writes the data to a buffer. The total number of bytes written into the buffer. This can be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached before any bytes are read. - . - - The `offset` parameter gives the offset of the first byte in `buffer` to which data from the current stream is written. The `count` parameter gives the maximum number of bytes to read from the current stream. The returned value is the actual number of bytes read, or zero if the end of the stream is reached. - - If the read operation is successful, the current position within the stream advances by the number of bytes read. If an exception occurs, the current position within the stream remains unchanged. - - The `Read` method will return zero only if the end of the stream is reached. In all other cases, `Read` always reads at least one byte from the stream before returning. By definition, if no data is available from the stream upon a call to `Read`, the `Read` method returns zero (the end of the stream is reached automatically). An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. - - Use for reading primitive data types. - + . + + The `offset` parameter gives the offset of the first byte in `buffer` to which data from the current stream is written. The `count` parameter gives the maximum number of bytes to read from the current stream. The returned value is the actual number of bytes read, or zero if the end of the stream is reached. + + If the read operation is successful, the current position within the stream advances by the number of bytes read. If an exception occurs, the current position within the stream remains unchanged. + + The `Read` method will return zero only if the end of the stream is reached. In all other cases, `Read` always reads at least one byte from the stream before returning. By definition, if no data is available from the stream upon a call to `Read`, the `Read` method returns zero (the end of the stream is reached automatically). An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. + + Use for reading primitive data types. + > [!CAUTION] -> If the byte array specified in the `buffer` parameter is the underlying buffer returned by the method, the array contents are overwritten, and no exception is thrown. - - - -## Examples - This code example is part of a larger example provided for the class. - +> If the byte array specified in the `buffer` parameter is the underlying buffer returned by the method, the array contents are overwritten, and no exception is thrown. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet7"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet7"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet7"::: + ]]> @@ -1891,6 +1893,7 @@ The pending operation does not support writing. Asynchronously reads a sequence of bytes from the current memory stream, writes the sequence into , advances the position within the memory stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous read operation. The value of its property contains the total number of bytes read into the . The result value can be less than the number of bytes allocated in if that many bytes are not currently available, or it can be 0 (zero) if the end of the memory stream has been reached. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1952,13 +1955,13 @@ The pending operation does not support writing. Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous read operation. The value of the parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - value for the property. - - You can create a cancellation token by creating an instance of the class and passing the property as the `cancellationToken` parameter. - + value for the property. + + You can create a cancellation token by creating an instance of the class and passing the property as the `cancellationToken` parameter. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1971,6 +1974,7 @@ The pending operation does not support writing. The stream does not support reading. The stream has been disposed. The stream is currently in use by a previous read operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2019,22 +2023,22 @@ The pending operation does not support writing. Reads a byte from the current stream. The byte cast to a , or -1 if the end of the stream has been reached. - . - - If the read operation is successful, the current position within the stream is advanced by one byte. If an exception occurs, the current position within the stream is unchanged. - - - -## Examples - This code example is part of a larger example provided for the class. - + . + + If the read operation is successful, the current position within the stream is advanced by one byte. If an exception occurs, the current position within the stream is unchanged. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet8"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet8"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet8"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet8"::: + ]]> The current stream instance is closed. @@ -2094,33 +2098,33 @@ The pending operation does not support writing. Sets the position within the current stream to the specified value. The new position within the stream, calculated by combining the initial reference point and the offset. - . - - Seeking to any location beyond the length of the stream is supported. - - Do not use the method to determine the new position in the stream if the was initialized with a non-zero offset. If you do, will return an inaccurate value. Instead, use the property to get the new position of the stream. - - - -## Examples - This code example is part of a larger example provided for the class. - + . + + Seeking to any location beyond the length of the stream is supported. + + Do not use the method to determine the new position in the stream if the was initialized with a non-zero offset. If you do, will return an inaccurate value. Instead, use the property to get the new position of the stream. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet6"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet6"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet6"::: + ]]> Seeking is attempted before the beginning of the stream. is greater than Int32.MaxValue. - There is an invalid . - - -or- - + There is an invalid . + + -or- + caused an arithmetic overflow. The current stream instance is closed. File and Stream I/O @@ -2176,22 +2180,22 @@ The pending operation does not support writing. The value at which to set the length. Sets the length of the current stream to the specified value. - . - - If the specified value is less than the current length of the stream, the stream is truncated. If after the truncation the current position within the stream is past the end of the stream, the method returns -1, the method reads zero bytes into the provided byte array, and and methods append specified bytes at the end of the stream, increasing its length. If the specified value is larger than the current capacity and the stream is resizable, the capacity is increased, and the current position within the stream is unchanged. If the length is increased, the contents of the stream between the old and the new length are initialized to zeros. - + . + + If the specified value is less than the current length of the stream, the stream is truncated. If after the truncation the current position within the stream is past the end of the stream, the method returns -1, the method reads zero bytes into the provided byte array, and and methods append specified bytes at the end of the stream, increasing its length. If the specified value is larger than the current capacity and the stream is resizable, the capacity is increased, and the current position within the stream is unchanged. If the length is increased, the contents of the stream between the old and the new length are initialized to zeros. + > [!NOTE] -> A instance must support writing for this method to work. Use the property to determine whether the current instance supports writing. For additional information, see . - +> A instance must support writing for this method to work. Use the property to determine whether the current instance supports writing. For additional information, see . + ]]> - The current stream is not resizable and is larger than the current capacity. - - -or- - + The current stream is not resizable and is larger than the current capacity. + + -or- + The current stream does not support writing. is negative or is greater than the maximum length of the , where the maximum length is (Int32.MaxValue - origin), and origin is the index into the underlying buffer at which the stream starts. @@ -2252,16 +2256,16 @@ The pending operation does not support writing. Writes the stream contents to a byte array, regardless of the property. A new byte array. - from the array. To get the entire buffer, use the method. - - This method returns a copy of the contents of the as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned. See the constructor for details. - + from the array. To get the entire buffer, use the method. + + This method returns a copy of the contents of the as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned. See the constructor for details. + > [!NOTE] -> This method works when the is closed. - +> This method works when the is closed. + ]]> File and Stream I/O @@ -2332,7 +2336,7 @@ The underlying buffer will not be exposed if the current `MemoryStream` instance - with the parameter `publiclyVisible` set to `false`. > [!NOTE] -> This method works when the memory stream is closed. +> This method works when the memory stream is closed. ]]> @@ -2444,32 +2448,32 @@ The underlying buffer will not be exposed if the current `MemoryStream` instance The maximum number of bytes to write. Writes a block of bytes to the current stream using data read from a buffer. - . - - The `offset` parameter gives the offset of the first byte in `buffer` to write from, and the `count` parameter gives the number of bytes to write. If the write operation is successful, the current position within the stream is advanced by the number of bytes written. If an exception occurs, the current position within the stream is unchanged. - - Except for a `MemoryStream` constructed with a byte[] parameter, write operations at the end of a `MemoryStream` expand the `MemoryStream`. - - - -## Examples - This code example is part of a larger example provided for the class. - + . + + The `offset` parameter gives the offset of the first byte in `buffer` to write from, and the `count` parameter gives the number of bytes to write. If the write operation is successful, the current position within the stream is advanced by the number of bytes written. If an exception occurs, the current position within the stream is unchanged. + + Except for a `MemoryStream` constructed with a byte[] parameter, write operations at the end of a `MemoryStream` expand the `MemoryStream`. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet3"::: + ]]> is . - The stream does not support writing. For additional information see . - - -or- - + The stream does not support writing. For additional information see . + + -or- + The current position is closer than bytes to the end of the stream, and the capacity cannot be modified. subtracted from the buffer length is less than . @@ -2529,6 +2533,7 @@ The underlying buffer will not be exposed if the current `MemoryStream` instance Asynchronously writes the sequence of bytes contained in into the current memory stream, advances the current position within this memory stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2590,13 +2595,13 @@ The underlying buffer will not be exposed if the current `MemoryStream` instance Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. - value for the property. - - You can create a cancellation token by creating an instance of the class and passing the property as the `cancellationToken` parameter. - + value for the property. + + You can create a cancellation token by creating an instance of the class and passing the property as the `cancellationToken` parameter. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -2609,6 +2614,7 @@ The underlying buffer will not be exposed if the current `MemoryStream` instance The stream does not support writing. The stream has been disposed. The stream is currently in use by a previous write operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2659,28 +2665,28 @@ The underlying buffer will not be exposed if the current `MemoryStream` instance The byte to write. Writes a byte to the current stream at the current position. - . - - Except for a `MemoryStream` constructed with a byte[] parameter, write operations at the end of a `MemoryStream` expand the `MemoryStream`. - - - -## Examples - This code example is part of a larger example provided for the class. - + . + + Except for a `MemoryStream` constructed with a byte[] parameter, write operations at the end of a `MemoryStream` expand the `MemoryStream`. + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.MemoryStream/CPP/memstream.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.IO/MemoryStream/Overview/memstream.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.MemoryStream/VB/memstream.vb" id="Snippet4"::: + ]]> - The stream does not support writing. For additional information see . - - -or- - + The stream does not support writing. For additional information see . + + -or- + The current position is at the end of the stream, and the capacity cannot be modified. The current stream is closed. File and Stream I/O @@ -2736,11 +2742,11 @@ The underlying buffer will not be exposed if the current `MemoryStream` instance The stream to write this memory stream to. Writes the entire contents of this memory stream to another stream. - on the underlying buffer of this stream. - + on the underlying buffer of this stream. + ]]> diff --git a/xml/System.IO/RandomAccess.xml b/xml/System.IO/RandomAccess.xml index ad877f52d98..57f36897494 100644 --- a/xml/System.IO/RandomAccess.xml +++ b/xml/System.IO/RandomAccess.xml @@ -17,7 +17,7 @@ Provides offset-based APIs for reading and writing files in a thread-safe manner. Only regular disk files are supported. Unseekable files, like pipes, are not supported. - + Synchronization and Overlapped Input and Output OVERLAPPED structure @@ -203,6 +203,7 @@ This method stores in the task it returns all non-usage exceptions that the meth was not opened for reading. An I/O error occurred. + The cancellation token was canceled. This exception is stored into the returned task. @@ -253,6 +254,7 @@ Position of the file is not advanced. was not opened for reading. An I/O error occurred. + The cancellation token was canceled. This exception is stored into the returned task. @@ -437,6 +439,7 @@ This method stores in the task it returns all non-usage exceptions that the meth was not opened for writing. An I/O error occurred. + The cancellation token was canceled. This exception is stored into the returned task. @@ -487,6 +490,7 @@ Position of the file is not advanced. was not opened for writing. An I/O error occurred. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO/Stream.xml b/xml/System.IO/Stream.xml index d03bbfd0e20..0e70d2e7151 100644 --- a/xml/System.IO/Stream.xml +++ b/xml/System.IO/Stream.xml @@ -80,50 +80,50 @@ Provides a generic view of a sequence of bytes. This is an abstract class. - is the abstract base class of all streams. A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. The class and its derived classes provide a generic view of these different types of input and output, and isolate the programmer from the specific details of the operating system and the underlying devices. - - Streams involve three fundamental operations: - -- You can read from streams. Reading is the transfer of data from a stream into a data structure, such as an array of bytes. - -- You can write to streams. Writing is the transfer of data from a data structure into a stream. - -- Streams can support seeking. Seeking refers to querying and modifying the current position within a stream. Seek capability depends on the kind of backing store a stream has. For example, network streams have no unified concept of a current position, and therefore typically do not support seeking. - - Some of the more commonly used streams that inherit from are , and . - - Depending on the underlying data source or repository, streams might support only some of these capabilities. You can query a stream for its capabilities by using the , , and properties of the class. - - The and methods read and write data in a variety of formats. For streams that support seeking, use the and methods and the and properties to query and modify the current position and length of a stream. - - This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - - Disposing a object flushes any buffered data, and essentially calls the method for you. also releases operating system resources such as file handles, network connections, or memory used for any internal buffering. The class provides the capability of wrapping a buffered stream around another stream in order to improve read and write performance. - - Starting with the .NET Framework 4.5, the class includes async methods to simplify asynchronous operations. An async method contains `Async` in its name, such as , , , and . These methods enable you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - When used in a Windows 8.x Store app, includes two extension methods: and . These methods convert a object to a stream in the Windows Runtime. You can also convert a stream in the Windows Runtime to a object by using the and methods. For more information, see [How to: Convert Between .NET Framework Streams and Windows Runtime Streams](/dotnet/standard/io/how-to-convert-between-dotnet-streams-and-winrt-streams) - - Some stream implementations perform local buffering of the underlying data to improve performance. For such streams, you can use the or method to clear any internal buffers and ensure that all data has been written to the underlying data source or repository. - - If you need a stream with no backing store (also known as a bit bucket), use the field to retrieve an instance of a stream that is designed for this purpose. - - - -## Examples - The following example demonstrates how to use two objects to asynchronously copy the files from one directory to another directory. The class derives from the class. Notice that the event handler for the control is marked with the `async` modifier because it calls an asynchronous method. - + is the abstract base class of all streams. A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. The class and its derived classes provide a generic view of these different types of input and output, and isolate the programmer from the specific details of the operating system and the underlying devices. + + Streams involve three fundamental operations: + +- You can read from streams. Reading is the transfer of data from a stream into a data structure, such as an array of bytes. + +- You can write to streams. Writing is the transfer of data from a data structure into a stream. + +- Streams can support seeking. Seeking refers to querying and modifying the current position within a stream. Seek capability depends on the kind of backing store a stream has. For example, network streams have no unified concept of a current position, and therefore typically do not support seeking. + + Some of the more commonly used streams that inherit from are , and . + + Depending on the underlying data source or repository, streams might support only some of these capabilities. You can query a stream for its capabilities by using the , , and properties of the class. + + The and methods read and write data in a variety of formats. For streams that support seeking, use the and methods and the and properties to query and modify the current position and length of a stream. + + This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. + + Disposing a object flushes any buffered data, and essentially calls the method for you. also releases operating system resources such as file handles, network connections, or memory used for any internal buffering. The class provides the capability of wrapping a buffered stream around another stream in order to improve read and write performance. + + Starting with the .NET Framework 4.5, the class includes async methods to simplify asynchronous operations. An async method contains `Async` in its name, such as , , , and . These methods enable you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + When used in a Windows 8.x Store app, includes two extension methods: and . These methods convert a object to a stream in the Windows Runtime. You can also convert a stream in the Windows Runtime to a object by using the and methods. For more information, see [How to: Convert Between .NET Framework Streams and Windows Runtime Streams](/dotnet/standard/io/how-to-convert-between-dotnet-streams-and-winrt-streams) + + Some stream implementations perform local buffering of the underlying data to improve performance. For such streams, you can use the or method to clear any internal buffers and ensure that all data has been written to the underlying data source or repository. + + If you need a stream with no backing store (also known as a bit bucket), use the field to retrieve an instance of a stream that is designed for this purpose. + + + +## Examples + The following example demonstrates how to use two objects to asynchronously copy the files from one directory to another directory. The class derives from the class. Notice that the event handler for the control is marked with the `async` modifier because it calls an asynchronous method. + :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/Overview/example.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Asynchronous_File_IO_async/vb/example.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Asynchronous_File_IO_async/vb/example.vb" id="Snippet1"::: + ]]> - When you implement a derived class of , you must provide implementations for the and methods. The asynchronous methods , , and use the synchronous methods and in their implementations. Therefore, your implementations of and will work correctly with the asynchronous methods. The default implementations of and create a new single-element byte array, and then call your implementations of and . When you derive from , we recommend that you override these methods to access your internal buffer, if you have one, for substantially better performance. You must also provide implementations of , , , , , , , and . - + When you implement a derived class of , you must provide implementations for the and methods. The asynchronous methods , , and use the synchronous methods and in their implementations. Therefore, your implementations of and will work correctly with the asynchronous methods. The default implementations of and create a new single-element byte array, and then call your implementations of and . When you derive from , we recommend that you override these methods to access your internal buffer, if you have one, for substantially better performance. You must also provide implementations of , , , , , , , and . + Do not override the method, instead, put all the cleanup logic in the method. For more information, see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). @@ -171,13 +171,13 @@ Initializes a new instance of the class. - is the abstract base class of all streams. - - Some of the more commonly used streams that inherit from are , and . - + is the abstract base class of all streams. + + Some of the more commonly used streams that inherit from are , and . + ]]> @@ -235,23 +235,23 @@ Begins an asynchronous read operation. (Consider using instead.) An that represents the asynchronous read, which could still be pending. - and to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - The default implementation of `BeginRead` on a stream calls the method synchronously, which means that `Read` might block on some streams. However, instances of classes such as `FileStream` and `NetworkStream` fully support asynchronous operations if the instances have been opened asynchronously. Therefore, calls to `BeginRead` will not block on those streams. You can override `BeginRead` (by using async delegates, for example) to provide asynchronous behavior. - - Pass the `IAsyncResult` return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . You can do this either by using the same code that called `BeginRead` or in a callback passed to `BeginRead`. - - The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. - - Multiple simultaneous asynchronous requests render the request completion order uncertain. - - Use the property to determine whether the current instance supports reading. - - If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginRead`. Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndRead`. - + and to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + + The default implementation of `BeginRead` on a stream calls the method synchronously, which means that `Read` might block on some streams. However, instances of classes such as `FileStream` and `NetworkStream` fully support asynchronous operations if the instances have been opened asynchronously. Therefore, calls to `BeginRead` will not block on those streams. You can override `BeginRead` (by using async delegates, for example) to provide asynchronous behavior. + + Pass the `IAsyncResult` return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . You can do this either by using the same code that called `BeginRead` or in a callback passed to `BeginRead`. + + The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. + + Multiple simultaneous asynchronous requests render the request completion order uncertain. + + Use the property to determine whether the current instance supports reading. + + If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginRead`. Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndRead`. + ]]> Attempted an asynchronous read past the end of the stream, or a disk error occurs. @@ -317,23 +317,23 @@ Begins an asynchronous write operation. (Consider using instead.) An that represents the asynchronous write, which could still be pending. - and to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - The default implementation of `BeginWrite` on a stream calls the method synchronously, which means that `Write` might block on some streams. However, instances of classes such as `FileStream` and `NetworkStream` fully support asynchronous operations if the instances have been opened asynchronously. Therefore, calls to `BeginWrite` will not block on those streams. You can override `BeginWrite` (by using async delegates, for example) to provide asynchronous behavior. - - Pass the `IAsyncResult` returned by the current method to to ensure that the write completes and frees resources appropriately. must be called once for every call to . You can do this either by using the same code that called `BeginWrite` or in a callback passed to `BeginWrite`. If an error occurs during an asynchronous write, an exception will not be thrown until `EndWrite` is called with the `IAsyncResult` returned by this method. - - If a stream is writable, writing at the end of the stream expands the stream. - - The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. - - Use the property to determine whether the current instance supports writing. - - If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginWrite`. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndWrite`. - + and to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + + The default implementation of `BeginWrite` on a stream calls the method synchronously, which means that `Write` might block on some streams. However, instances of classes such as `FileStream` and `NetworkStream` fully support asynchronous operations if the instances have been opened asynchronously. Therefore, calls to `BeginWrite` will not block on those streams. You can override `BeginWrite` (by using async delegates, for example) to provide asynchronous behavior. + + Pass the `IAsyncResult` returned by the current method to to ensure that the write completes and frees resources appropriately. must be called once for every call to . You can do this either by using the same code that called `BeginWrite` or in a callback passed to `BeginWrite`. If an error occurs during an asynchronous write, an exception will not be thrown until `EndWrite` is called with the `IAsyncResult` returned by this method. + + If a stream is writable, writing at the end of the stream expands the stream. + + The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. + + Use the property to determine whether the current instance supports writing. + + If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginWrite`. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndWrite`. + ]]> Attempted an asynchronous write past the end of the stream, or a disk error occurs. @@ -391,20 +391,20 @@ if the stream supports reading; otherwise, . - does not support reading, calls to the , , and methods throw a . - - - -## Examples - The following is an example of using the `CanRead` property. - + does not support reading, calls to the , , and methods throw a . + + + +## Examples + The following is an example of using the `CanRead` property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_Classic/classic FileStream.CanRead Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/CanRead/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic FileStream.CanRead Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic FileStream.CanRead Example/VB/source.vb" id="Snippet1"::: + ]]> File and Stream I/O @@ -455,11 +455,11 @@ if the stream supports seeking; otherwise, . - does not support seeking, calls to , , , and may throw a . - + does not support seeking, calls to , , , and may throw a . + ]]> File and Stream I/O @@ -514,11 +514,11 @@ Gets a value that determines whether the current stream can time out. A value that determines whether the current stream can time out. - property always returns `false`. Some stream implementations require different behavior, such as , which times out if network connectivity is interrupted or lost. If you are implementing a stream that must be able to time out, this property should be overridden to return `true`. - + property always returns `false`. Some stream implementations require different behavior, such as , which times out if network connectivity is interrupted or lost. If you are implementing a stream that must be able to time out, this property should be overridden to return `true`. + ]]> @@ -568,20 +568,20 @@ if the stream supports writing; otherwise, . - does not support writing, a call to , , or throws a . In such cases, is typically implemented as an empty method to ensure full compatibility with other types since it's valid to flush a read-only stream. - - - -## Examples - The following is an example of using the `CanWrite` property. - + + + +## Examples + The following is an example of using the `CanWrite` property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_Classic/classic Stream.CanWrite Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Stream/CanWrite/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic Stream.CanWrite Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic Stream.CanWrite Example/VB/source.vb" id="Snippet1"::: + ]]> File and Stream I/O @@ -628,15 +628,15 @@ Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed. - , specifying `true` to release all resources. You do not have to specifically call the method. Instead, ensure that every object is properly disposed. You can declare objects within a `using` block (or `Using` block in Visual Basic) to ensure that the stream and all of its resources are disposed, or you can explicitly call the method. - - Flushing the stream will not flush its underlying encoder unless you explicitly call an implementation of or `Close`. Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can be encoded only after the encoder receives the adjacent character or characters. - - Attempts to manipulate the stream after the stream has been closed might throw an . - + , specifying `true` to release all resources. You do not have to specifically call the method. Instead, ensure that every object is properly disposed. You can declare objects within a `using` block (or `Using` block in Visual Basic) to ensure that the stream and all of its resources are disposed, or you can explicitly call the method. + + Flushing the stream will not flush its underlying encoder unless you explicitly call an implementation of or `Close`. Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can be encoded only after the encoder receives the adjacent character or characters. + + Attempts to manipulate the stream after the stream has been closed might throw an . + ]]> @@ -701,27 +701,27 @@ The stream to which the contents of the current stream will be copied. Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied. - to a . - + to a . + :::code language="csharp" source="~/snippets/csharp/System.IO/Stream/CopyTo/program.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stream.copyto/vb/program.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stream.copyto/vb/program.vb" id="Snippet1"::: + ]]> is . - The current stream does not support reading. - - -or- - + The current stream does not support reading. + + -or- + does not support writing. Either the current stream or were closed before the method was called. An I/O error occurred. @@ -777,21 +777,21 @@ The size of the buffer. This value must be greater than zero. The default size is 81920. Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied. - is . is negative or zero. - The current stream does not support reading. - - -or- - + The current stream does not support reading. + + -or- + does not support writing. Either the current stream or were closed before the method was called. An I/O error occurred. @@ -858,18 +858,18 @@ Asynchronously reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied. A task that represents the asynchronous copy operation. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - Copying begins at the current position in the current stream. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + Copying begins at the current position in the current stream. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example demonstrates how to use two objects to asynchronously copy the files from one directory to another. The class derives from the class. Notice that the event handler for the control is marked with the `async` modifier because it calls an asynchronous method - + +## Examples + The following example demonstrates how to use two objects to asynchronously copy the files from one directory to another. The class derives from the class. Notice that the event handler for the control is marked with the `async` modifier because it calls an asynchronous method + :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/Overview/example.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Asynchronous_File_IO_async/vb/example.vb" id="Snippet1"::: @@ -933,15 +933,15 @@ Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied. A task that represents the asynchronous copy operation. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - Copying begins at the current position in the current stream. - - For an example of copying between two streams, see the overload. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + Copying begins at the current position in the current stream. + + For an example of copying between two streams, see the overload. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -993,21 +993,22 @@ Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token. Both streams positions are advanced by the number of bytes copied. A task that represents the asynchronous copy operation. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - If the operation is canceled before it completes, the returned task contains the value for the property. - - Copying begins at the current position in the current stream. - - For an example of copying between two streams, see the overload. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + If the operation is canceled before it completes, the returned task contains the value for the property. + + Copying begins at the current position in the current stream. + + For an example of copying between two streams, see the overload. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1064,17 +1065,17 @@ Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token. Both streams positions are advanced by the number of bytes copied. A task that represents the asynchronous copy operation. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - If the operation is canceled before it completes, the returned task contains the value for the property. - - Copying begins at the current position in the current stream. - - For an example of copying between two streams, see the overload. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + If the operation is canceled before it completes, the returned task contains the value for the property. + + Copying begins at the current position in the current stream. + + For an example of copying between two streams, see the overload. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1085,6 +1086,7 @@ is negative or zero. Either the current stream or the destination stream is disposed. The current stream does not support reading, or the destination stream does not support writing. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1141,13 +1143,13 @@ Allocates a object. A reference to the allocated . - or until the asynchronous operation is complete. - + or until the asynchronous operation is complete. + ]]> File and Stream I/O @@ -1210,18 +1212,18 @@ Releases all resources used by the . - to be reallocated for other purposes. For more information about `Dispose`, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). - + to be reallocated for other purposes. For more information about `Dispose`, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). + ]]> - Place all cleanup logic for your stream object in . Do not override . - + Place all cleanup logic for your stream object in . Do not override . + Note that because of backward compatibility requirements, this method's implementation differs from the recommended guidance for the Dispose pattern. This method calls , which then calls . @@ -1271,22 +1273,22 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - for this purpose. - - This method is called by the public method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. - + for this purpose. + + This method is called by the public method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. + ]]> - In derived classes, do not override the method, instead, put all of the Stream cleanup logic in the method. - - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + In derived classes, do not override the method, instead, put all of the Stream cleanup logic in the method. + + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). @@ -1328,15 +1330,15 @@ Asynchronously releases the unmanaged resources used by the . A task that represents the asynchronous dispose operation. - method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - This method disposes the stream by writing any changes to the backing store and closing the stream to release resources. - - Calling `DisposeAsync` allows the resources used by the to be reallocated for other purposes. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). - + method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + This method disposes the stream by writing any changes to the backing store and closing the stream to release resources. + + Calling `DisposeAsync` allows the resources used by the to be reallocated for other purposes. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1386,25 +1388,25 @@ Waits for the pending asynchronous read to complete. (Consider using instead.) The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams return zero (0) only at the end of the stream, otherwise, they should block until at least one byte is available. - and to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - Call `EndRead` to determine how many bytes were read from the stream. - - `EndRead` can be called once on every from . - - This method blocks until the I/O operation has completed. - + and to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + + Call `EndRead` to determine how many bytes were read from the stream. + + `EndRead` can be called once on every from . + + This method blocks until the I/O operation has completed. + ]]> is . - A handle to the pending read operation is not available. - - -or- - + A handle to the pending read operation is not available. + + -or- + The pending operation does not support reading. did not originate from a method on the current stream. @@ -1457,23 +1459,23 @@ A reference to the outstanding asynchronous I/O request. Ends an asynchronous write operation. (Consider using instead.) - and to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - `EndWrite` must be called exactly once on every from . - - This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to `EndWrite`. Exceptions thrown by the thread pool thread will not be visible when calling `EndWrite`. - + and to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + + `EndWrite` must be called exactly once on every from . + + This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to `EndWrite`. Exceptions thrown by the thread pool thread will not be visible when calling `EndWrite`. + ]]> is . - A handle to the pending write operation is not available. - - -or- - + A handle to the pending write operation is not available. + + -or- + The pending operation does not support writing. did not originate from a method on the current stream. @@ -1526,15 +1528,15 @@ When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device. - . + . In a class derived from that doesn't support writing, is typically implemented as an empty method to ensure full compatibility with other types since it's valid to flush a read-only stream. - When using the or class, do not flush the base object. Instead, use the class's or method, which makes sure that the data is flushed to the underlying stream first and then written to the file. - + When using the or class, do not flush the base object. Instead, use the class's or method, which makes sure that the data is flushed to the underlying stream first and then written to the file. + ]]> An I/O error occurs. @@ -1601,11 +1603,11 @@ Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device. A task that represents the asynchronous flush operation. - or , does not flush the buffer in its implementation of the method, the method will not flush the buffer. - + or , does not flush the buffer in its implementation of the method, the method will not flush the buffer. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1663,19 +1665,20 @@ Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. A task that represents the asynchronous flush operation. - value for the property. - - If a derived class, such as or , does not flush the buffer in its implementation of the method, the method will not flush the buffer. - + value for the property. + + If a derived class, such as or , does not flush the buffer in its implementation of the method, the method will not flush the buffer. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> The stream has been disposed. Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1768,11 +1771,11 @@ A with no backing store. - File and Stream I/O @@ -1867,13 +1870,13 @@ When overridden in a derived class, gets or sets the position within the current stream. The current position within the stream. - property to determine whether the stream supports seeking. - - Seeking to any location beyond the length of the stream is supported. - + property to determine whether the stream supports seeking. + + Seeking to any location beyond the length of the stream is supported. + ]]> An I/O error occurs. @@ -1921,15 +1924,15 @@ When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. The total number of bytes read into the buffer. This can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. - property to determine whether the current instance supports reading. Use the method to read asynchronously from the current stream. - - Implementations of this method read a maximum of `buffer.Length` bytes from the current stream and store them in `buffer`. The current position within the stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the stream remains unchanged. Implementations return the number of bytes read. The implementation will block until at least one byte of data can be read, in the event that no data is available. returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. - - Use for reading primitive data types. - + property to determine whether the current instance supports reading. Use the method to read asynchronously from the current stream. + + Implementations of this method read a maximum of `buffer.Length` bytes from the current stream and store them in `buffer`. The current position within the stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the stream remains unchanged. Implementations return the number of bytes read. The implementation will block until at least one byte of data can be read, in the event that no data is available. returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. + + Use for reading primitive data types. + ]]> @@ -1985,24 +1988,24 @@ When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. - property to determine whether the current instance supports reading. Use the method to read asynchronously from the current stream. - - Implementations of this method read a maximum of `count` bytes from the current stream and store them in `buffer` beginning at `offset`. The current position within the stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the stream remains unchanged. Implementations return the number of bytes read. The implementation will block until at least one byte of data can be read, in the event that no data is available. returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. - - Use for reading primitive data types. - - - -## Examples - The following example shows how to use to read a block of data. - + property to determine whether the current instance supports reading. Use the method to read asynchronously from the current stream. + + Implementations of this method read a maximum of `count` bytes from the current stream and store them in `buffer` beginning at `offset`. The current position within the stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the stream remains unchanged. Implementations return the number of bytes read. The implementation will block until at least one byte of data can be read, in the event that no data is available. returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. + + Use for reading primitive data types. + + + +## Examples + The following example shows how to use to read a block of data. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_Classic/classic Stream.Read Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Stream/Read/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic Stream.Read Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic Stream.Read Example/VB/source.vb" id="Snippet1"::: + ]]> The sum of and is larger than the buffer length. @@ -2067,19 +2070,20 @@ Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous read operation. The value of its property contains the total number of bytes read into the buffer. The result value can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or it can be 0 (zero) if the end of the stream has been reached. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - Use the property to determine whether the current instance supports reading. - - If the operation is canceled before it completes, the returned task contains the value for the property. - - For an example, see the overload. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + Use the property to determine whether the current instance supports reading. + + If the operation is canceled before it completes, the returned task contains the value for the property. + + For an example, see the overload. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -2136,18 +2140,18 @@ Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. A task that represents the asynchronous read operation. The value of the parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - Use the property to determine whether the current instance supports reading. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + Use the property to determine whether the current instance supports reading. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to read from a file asynchronously. The example uses the class, which derives from the class. - + +## Examples + The following example shows how to read from a file asynchronously. The example uses the class, which derives from the class. + :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/Overview/example4.cs" id="Snippet4"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Asynchronous_File_IO_async/vb/example4.vb" id="Snippet4"::: @@ -2219,17 +2223,17 @@ Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous read operation. The value of the parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - Use the property to determine whether the current instance supports reading. - - If the operation is canceled before it completes, the returned task contains the value for the property. - - For an example, see the overload. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + Use the property to determine whether the current instance supports reading. + + If the operation is canceled before it completes, the returned task contains the value for the property. + + For an example, see the overload. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -2243,6 +2247,7 @@ The stream has been disposed. The stream is currently in use by a previous read operation. Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -2349,6 +2354,7 @@ When `minimumBytes` is 0 (zero), this read operation will be completed without w is and the end of the stream is reached before reading bytes of data. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2400,13 +2406,13 @@ When `minimumBytes` is 0 (zero), this read operation will be completed without w Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. The unsigned byte cast to an , or -1 if at the end of the stream. - property to determine whether the current instance supports reading. - - Attempts to manipulate the stream after the stream has been closed could throw an . - + property to determine whether the current instance supports reading. + + Attempts to manipulate the stream after the stream has been closed could throw an . + ]]> The stream does not support reading. @@ -2562,6 +2568,7 @@ When `buffer` is empty, this read operation will be completed without waiting fo ]]> The end of the stream is reached before filling the . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2625,6 +2632,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The range specified by the combination of and exceeds the length of . The end of the stream is reached before reading number of bytes. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2728,17 +2736,17 @@ The range specified by the combination of and When overridden in a derived class, sets the position within the current stream. The new position within the current stream. - property to determine whether the current instance supports seeking. - - If `offset` is negative, the new position is required to precede the position specified by `origin` by the number of bytes specified by `offset`. If `offset` is zero (0), the new position is required to be the position specified by `origin`. If `offset` is positive, the new position is required to follow the position specified by `origin` by the number of bytes specified by `offset`. - - Classes derived from `Stream` that support seeking must override this method to provide the functionality described above. - - Seeking to any location beyond the length of the stream is supported. - + property to determine whether the current instance supports seeking. + + If `offset` is negative, the new position is required to precede the position specified by `origin` by the number of bytes specified by `offset`. If `offset` is zero (0), the new position is required to be the position specified by `origin`. If `offset` is positive, the new position is required to follow the position specified by `origin` by the number of bytes specified by `offset`. + + Classes derived from `Stream` that support seeking must override this method to provide the functionality described above. + + Seeking to any location beyond the length of the stream is supported. + ]]> An I/O error occurs. @@ -2794,15 +2802,15 @@ The range specified by the combination of and The desired length of the current stream in bytes. When overridden in a derived class, sets the length of the current stream. - property to determine whether the current instance supports writing, and the property to determine whether seeking is supported. - + property to determine whether the current instance supports writing, and the property to determine whether seeking is supported. + ]]> An I/O error occurs. @@ -2855,11 +2863,11 @@ The range specified by the combination of and Creates a thread-safe (synchronized) wrapper around the specified object. A thread-safe object. - object and restricts access to it from multiple threads. All access to the object will be thread safe. - + object and restricts access to it from multiple threads. All access to the object will be thread safe. + ]]> @@ -2899,7 +2907,7 @@ The range specified by the combination of and instance is cast to an interface. ]]> @@ -3028,13 +3036,13 @@ This member is an explicit interface member implementation. It can be used only A region of memory. This method copies the contents of this region to the current stream. When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. - property to determine whether the current instance supports writing. Use the method to write asynchronously to the current stream. - - If the write operation is successful, the position within the stream advances by the number of bytes written. If an exception occurs, the position within the stream remains unchanged. - + property to determine whether the current instance supports writing. Use the method to write asynchronously to the current stream. + + If the write operation is successful, the position within the stream advances by the number of bytes written. If an exception occurs, the position within the stream remains unchanged. + ]]> @@ -3088,13 +3096,13 @@ This member is an explicit interface member implementation. It can be used only The number of bytes to be written to the current stream. When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. - property to determine whether the current instance supports writing. Use the method to write asynchronously to the current stream. - - If the write operation is successful, the position within the stream advances by the number of bytes written. If an exception occurs, the position within the stream remains unchanged. - + property to determine whether the current instance supports writing. Use the method to write asynchronously to the current stream. + + If the write operation is successful, the position within the stream advances by the number of bytes written. If an exception occurs, the position within the stream remains unchanged. + ]]> The sum of and is greater than the buffer length. @@ -3160,19 +3168,20 @@ This member is an explicit interface member implementation. It can be used only Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - Use the property to determine whether the current instance supports writing. - - If the operation is canceled before it completes, the returned task contains the value for the property. - - For an example, see the overload. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + Use the property to determine whether the current instance supports writing. + + If the operation is canceled before it completes, the returned task contains the value for the property. + + For an example, see the overload. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -3229,18 +3238,18 @@ This member is an explicit interface member implementation. It can be used only Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. A task that represents the asynchronous write operation. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - Use the property to determine whether the current instance supports writing. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + Use the property to determine whether the current instance supports writing. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to write asynchronously to a file. The example uses the class, which derives from the class. - + +## Examples + The following example shows how to write asynchronously to a file. The example uses the class, which derives from the class. + :::code language="csharp" source="~/snippets/csharp/System.IO/FileStream/Overview/example3.cs" id="Snippet3"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Asynchronous_File_IO_async/vb/example3.vb" id="Snippet3"::: @@ -3312,17 +3321,17 @@ This member is an explicit interface member implementation. It can be used only Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. - method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - Use the property to determine whether the current instance supports writing. - - If the operation is canceled before it completes, the returned task contains the value for the property. - - For an example, see the overload. - + method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + Use the property to determine whether the current instance supports writing. + + If the operation is canceled before it completes, the returned task contains the value for the property. + + For an example, see the overload. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -3336,6 +3345,7 @@ This member is an explicit interface member implementation. It can be used only The stream has been disposed. The stream is currently in use by a previous write operation. Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -3383,11 +3393,11 @@ This member is an explicit interface member implementation. It can be used only The byte to write to the stream. Writes a byte to the current position in the stream and advances the position within the stream by one byte. - property to determine whether the current instance supports writing. - + property to determine whether the current instance supports writing. + ]]> An I/O error occurs. diff --git a/xml/System.IO/StreamReader.xml b/xml/System.IO/StreamReader.xml index b4882806ea8..284e60b3684 100644 --- a/xml/System.IO/StreamReader.xml +++ b/xml/System.IO/StreamReader.xml @@ -68,39 +68,39 @@ Implements a that reads characters from a byte stream in a particular encoding. - is designed for character input in a particular encoding, whereas the class is designed for byte input and output. Use for reading lines of information from a standard text file. - + is designed for character input in a particular encoding, whereas the class is designed for byte input and output. Use for reading lines of information from a standard text file. + > [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - - defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system. UTF-8 handles Unicode characters correctly and provides consistent results on localized versions of the operating system. If you get the current character encoding using the property, the value is not reliable until after the first method, since encoding auto detection is not done until the first call to a method. - - By default, a is not thread safe. See for a thread-safe wrapper. - - The and method overloads read and write the number of characters specified by the `count` parameter. These are to be distinguished from and , which read and write the number of bytes specified by the `count` parameter. Use the methods only for reading and writing an integral number of byte array elements. - +> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. + + defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system. UTF-8 handles Unicode characters correctly and provides consistent results on localized versions of the operating system. If you get the current character encoding using the property, the value is not reliable until after the first method, since encoding auto detection is not done until the first call to a method. + + By default, a is not thread safe. See for a thread-safe wrapper. + + The and method overloads read and write the number of characters specified by the `count` parameter. These are to be distinguished from and , which read and write the number of bytes specified by the `count` parameter. Use the methods only for reading and writing an integral number of byte array elements. + > [!NOTE] -> When reading from a , it is more efficient to use a buffer that is the same size as the internal buffer of the stream. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example uses an instance of to read text from a file. The constructor used in this example is not supported for use in Windows Store Apps. - +> When reading from a , it is more efficient to use a buffer that is the same size as the internal buffer of the stream. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example uses an instance of to read text from a file. The constructor used in this example is not supported for use in Windows Store Apps. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/ReadTextFile/CPP/readtextfile.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/readtextfile.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/ReadTextFile/VB/readtextfile.vb" id="Snippet1"::: - - The following example instantiates a object and calls its method to read a file asynchronously. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/ReadTextFile/VB/readtextfile.vb" id="Snippet1"::: + + The following example instantiates a object and calls its method to read a file asynchronously. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/asyncex1.cs" id="Snippet51"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/asyncex1.vb" id="Snippet51"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/asyncex1.vb" id="Snippet51"::: + ]]> @@ -168,27 +168,27 @@ The stream to be read. Initializes a new instance of the class for the specified stream. - , the property using the `stream` parameter, and the internal buffer size to 1024 bytes. - - The object calls on the provided object when is called. - + , the property using the `stream` parameter, and the internal buffer size to 1024 bytes. + + The object calls on the provided object when is called. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/StrmReader Ctor1/CPP/strmreader ctor1.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/.ctor/strmreader ctor1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Ctor1/VB/strmreader ctor1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Ctor1/VB/strmreader ctor1.vb" id="Snippet1"::: + ]]> @@ -248,29 +248,29 @@ The complete file path to be read. Initializes a new instance of the class for the specified file name. - and the buffer size to 1024 bytes. - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. - - The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. - + and the buffer size to 1024 bytes. + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. + + The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/StrmReader Ctor2/CPP/strmreader ctor2.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/.ctor/strmreader ctor2.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Ctor2/VB/strmreader ctor2.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Ctor2/VB/strmreader ctor2.vb" id="Snippet1"::: + ]]> @@ -334,26 +334,26 @@ Indicates whether to look for byte order marks at the beginning of the file. Initializes a new instance of the class for the specified stream, with the specified byte order mark detection option. - , the property using the `stream` parameter, and the internal buffer size to 1024 bytes. - - The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. See the method for more information. - - The object calls on the provided object when is called. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - + , the property using the `stream` parameter, and the internal buffer size to 1024 bytes. + + The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. See the method for more information. + + The object calls on the provided object when is called. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamReader/CPP/streamreadersample.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/streamreadersample.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: + ]]> @@ -412,27 +412,27 @@ The character encoding to use. Initializes a new instance of the class for the specified stream, with the specified character encoding. - object attempts to detect the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. - - The object calls on the provided object when is called. - + object attempts to detect the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. + + The object calls on the provided object when is called. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamReader/CPP/streamreadersample.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/streamreadersample.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: + ]]> @@ -495,28 +495,28 @@ Indicates whether to look for byte order marks at the beginning of the file. Initializes a new instance of the class for the specified file name, with the specified byte order mark detection option. - , the property using the `stream` parameter, and the internal buffer size to 1024 bytes. - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. - - The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. - - The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the is used. See the method for more information. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - + , the property using the `stream` parameter, and the internal buffer size to 1024 bytes. + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. + + The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. + + The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the is used. See the method for more information. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamReader/CPP/streamreadersample.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/streamreadersample.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: + ]]> @@ -634,29 +634,29 @@ The character encoding to use. Initializes a new instance of the class for the specified file name, with the specified character encoding. - object attempts to detect the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. - - The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. - + object attempts to detect the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. + + The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamReader/CPP/streamreadersample.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/streamreadersample.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: + ]]> @@ -722,29 +722,29 @@ Indicates whether to look for byte order marks at the beginning of the file. Initializes a new instance of the class for the specified stream, with the specified character encoding and byte order mark detection option. - property using the `stream` parameter, and the internal buffer size to 1024 bytes. - - The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. - - The object calls on the provided object when is called. - + property using the `stream` parameter, and the internal buffer size to 1024 bytes. + + The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. + + The object calls on the provided object when is called. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamReader/CPP/streamreadersample.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/streamreadersample.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: + ]]> @@ -809,31 +809,31 @@ Indicates whether to look for byte order marks at the beginning of the file. Initializes a new instance of the class for the specified file name, with the specified character encoding and byte order mark detection option. - method for more information. - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. - - The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. - + method for more information. + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. + + The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamReader/CPP/streamreadersample.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/streamreadersample.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: + ]]> @@ -901,32 +901,32 @@ The minimum buffer size. Initializes a new instance of the class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size. - object. The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. - - The object calls on the provided object when is called. - + object. The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. + + The object calls on the provided object when is called. + > [!NOTE] -> When reading from a , it is more efficient to use a buffer that is the same size as the internal buffer of the stream. - +> When reading from a , it is more efficient to use a buffer that is the same size as the internal buffer of the stream. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamReader/CPP/streamreadersample.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/streamreadersample.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: + ]]> The stream does not support reading. @@ -994,33 +994,33 @@ The minimum buffer size, in number of 16-bit characters. Initializes a new instance of the class for the specified file name, with the specified character encoding, byte order mark detection option, and buffer size. - object. The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. - - The buffer size, in number of 16-bit characters, is set by the `bufferSize` parameter. If `bufferSize` is less than the minimum allowable size (128 characters), the minimum allowable size is used. - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. - - The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. - + object. The `detectEncodingFromByteOrderMarks` parameter detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. + + The buffer size, in number of 16-bit characters, is set by the `bufferSize` parameter. If `bufferSize` is less than the minimum allowable size (128 characters), the minimum allowable size is used. + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. + + The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamReader/CPP/streamreadersample.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/streamreadersample.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/streamreadersample.vb" id="Snippet2"::: + ]]> @@ -1150,21 +1150,21 @@ to leave the stream open after the object is disposed; otherwise, . Initializes a new instance of the class for the specified stream based on the specified character encoding, byte order mark detection option, and buffer size, and optionally leaves the stream open. - object calls on the provided object when is called. - - The buffer size, in number of 16-bit characters, is set by the `bufferSize` parameter. If `bufferSize` is less than the minimum allowable size (128 characters), the minimum allowable size is used. - - This constructor enables you to change the encoding the first time you read from the object. If the `detectEncodingFromByteOrderMarks` parameter is `true`, the constructor detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. - + object calls on the provided object when is called. + + The buffer size, in number of 16-bit characters, is set by the `bufferSize` parameter. If `bufferSize` is less than the minimum allowable size (128 characters), the minimum allowable size is used. + + This constructor enables you to change the encoding the first time you read from the object. If the `detectEncodingFromByteOrderMarks` parameter is `true`, the constructor detects the encoding by looking at the first four bytes of the stream. It automatically recognizes UTF-8, little-endian UTF-16, big-endian UTF-16, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the method for more information. + > [!NOTE] -> When reading from a , it is more efficient to use a buffer that is the same size as the internal buffer of the stream. - +> When reading from a , it is more efficient to use a buffer that is the same size as the internal buffer of the stream. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpreted correctly, and could cause an exception to be thrown. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpreted correctly, and could cause an exception to be thrown. + ]]> @@ -1214,13 +1214,13 @@ Returns the underlying stream. The underlying stream. - class buffers input from the underlying stream when you call one of the methods. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. The constructors that have the `detectEncodingFromByteOrderMarks` parameter can change the encoding the first time you read from the object. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + class buffers input from the underlying stream when you call one of the methods. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. The constructors that have the `detectEncodingFromByteOrderMarks` parameter can change the encoding the first time you read from the object. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> File and Stream I/O @@ -1270,16 +1270,16 @@ Closes the object and the underlying stream, and releases any system resources associated with the reader. - method. - -This implementation of calls the method, passing a `true` value. - -Following a call to , any operations on the reader might raise exceptions. - + method. + +This implementation of calls the method, passing a `true` value. + +Following a call to , any operations on the reader might raise exceptions. + ]]> File and Stream I/O @@ -1332,20 +1332,20 @@ Following a call to , any operations on th Gets the current character encoding that the current object is using. The current character encoding used by the current reader. The value can be different after the first call to any method of , since encoding autodetection is not done until the first call to a method. - object. - + object. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/StrmReader CurrentEncoding/CPP/strmreader currentencoding.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/CurrentEncoding/strmreader currentencoding.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader CurrentEncoding/VB/strmreader currentencoding.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader CurrentEncoding/VB/strmreader currentencoding.vb" id="Snippet1"::: + ]]> File and Stream I/O @@ -1398,21 +1398,21 @@ Following a call to , any operations on th Clears the internal buffer. - method to reset the internal buffer for the object. You need to call this method only when the position of the internal buffer and the do not match. These positions can become mismatched when you read data into the buffer and then seek a new position in the underlying stream. This method slows performance and should be used only when absolutely necessary, such as when you want to read a portion of the contents of a object more than once. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example shows a scenario where the method must be called to synchronize the internal buffer and the underlying stream. The file in the example is used to illustrate position and consists of the text `abcdefghijklmnopqrstuvwxyz`. By calling after the data is read, the example works as expected. After the first 15 characters are read, the position is reset to the offset value of 2 and all the remaining characters are read. If you remove the call to , the example does not work as expected. The first 15 characters are read, but only the position of the underlying stream is reset. The internal buffer of the object is still on the 16th character. Therefore, returns all the characters in the buffer plus the characters in the underlying stream starting from the reset position. - + method to reset the internal buffer for the object. You need to call this method only when the position of the internal buffer and the do not match. These positions can become mismatched when you read data into the buffer and then seek a new position in the underlying stream. This method slows performance and should be used only when absolutely necessary, such as when you want to read a portion of the contents of a object more than once. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example shows a scenario where the method must be called to synchronize the internal buffer and the underlying stream. The file in the example is used to illustrate position and consists of the text `abcdefghijklmnopqrstuvwxyz`. By calling after the data is read, the example works as expected. After the first 15 characters are read, the position is reset to the offset value of 2 and all the remaining characters are read. If you remove the call to , the example does not work as expected. The first 15 characters are read, but only the position of the underlying stream is reset. The internal buffer of the object is still on the 16th character. Therefore, returns all the characters in the buffer plus the characters in the underlying stream starting from the reset position. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/program.cs" id="Snippet30"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/module1.vb" id="Snippet30"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/module1.vb" id="Snippet30"::: + ]]> File and Stream I/O @@ -1469,20 +1469,20 @@ Following a call to , any operations on th to release both managed and unmanaged resources; to release only unmanaged resources. Closes the underlying stream, releases the unmanaged resources used by the , and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to true. `Finalize` invokes with `disposing` set to false. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that the object references. This method invokes the method of each referenced object. - - . - + method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to true. `Finalize` invokes with `disposing` set to false. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that the object references. This method invokes the method of each referenced object. + + . + ]]> - Dispose can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to Dispose[cref,...]. For more information about how to implement see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + Dispose can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to Dispose[cref,...]. For more information about how to implement see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). File and Stream I/O @@ -1588,13 +1588,13 @@ Following a call to , any operations on th A object around an empty stream. - , zero is always returned. When is invoked on , `null` is returned. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + , zero is always returned. When is invoked on , `null` is returned. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> File and Stream I/O @@ -1654,24 +1654,24 @@ Following a call to , any operations on th Returns the next available character but does not consume it. An integer representing the next character to be read, or -1 if there are no characters to be read or if the stream does not support seeking. - method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a type. - - This method overrides . - - The current position of the object is not changed by . - - - -## Examples - The following code example reads lines from a file until the end of the file is reached. - + method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a type. + + This method overrides . + + The current position of the object is not changed by . + + + +## Examples + The following code example reads lines from a file until the end of the file is reached. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/StrmReader Peek/CPP/strmreader peek.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Peek/strmreader peek.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Peek/VB/strmreader peek.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Peek/VB/strmreader peek.vb" id="Snippet1"::: + ]]> An I/O error occurs. @@ -1743,30 +1743,30 @@ Following a call to , any operations on th Reads the next character from the input stream and advances the character position by one character. The next character from the input stream represented as an object, or -1 if no more characters are available. - . - - This method returns an integer so that it can return -1 if the end of the stream has been reached. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates a simple use of the method. - + . + + This method returns an integer so that it can return -1 if the end of the stream has been reached. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates a simple use of the method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/StrmReader Read1/CPP/strmreader read1.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Read/strmreader read1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Read1/VB/strmreader read1.vb" id="Snippet1"::: - - The following code example demonstrates reading a single character using the method overload, formatting the ASCII integer output as decimal and hexadecimal. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Read1/VB/strmreader read1.vb" id="Snippet1"::: + + The following code example demonstrates reading a single character using the method overload, formatting the ASCII integer output as decimal and hexadecimal. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/StrmRdrRead/CPP/strmrdrread.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Read/strmrdrread.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmRdrRead/VB/strmrdrread.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmRdrRead/VB/strmrdrread.vb" id="Snippet1"::: + ]]> An I/O error occurs. @@ -1880,28 +1880,28 @@ Following a call to , any operations on th Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index. The number of characters that have been read, or 0 if at the end of the stream and no data was read. The number will be less than or equal to the parameter, depending on whether the data is available within the stream. - . - - This method returns an integer so that it can return 0 if the end of the stream has been reached. - - When using the method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes). If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. - - This method returns after either the number of characters specified by the `count` parameter are read, or the end of the file is reached. is a blocking version of . - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example reads five characters at a time until the end of the file is reached. - + . + + This method returns an integer so that it can return 0 if the end of the stream has been reached. + + When using the method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes). If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. + + This method returns after either the number of characters specified by the `count` parameter are read, or the end of the file is reached. is a blocking version of . + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example reads five characters at a time until the end of the file is reached. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/StrmReader Read2/CPP/strmreader read2.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Read/strmreader read2.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Read2/VB/strmreader read2.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader Read2/VB/strmreader read2.vb" id="Snippet1"::: + ]]> The buffer length minus is less than . @@ -1956,6 +1956,7 @@ Following a call to , any operations on th Asynchronously reads the characters from the current stream into a memory block. A value task that represents the asynchronous read operation. The value of the type parameter of the value task contains the number of characters that have been read, or 0 if at the end of the stream and no data was read. The number will be less than or equal to the length, depending on whether the data is available within the stream. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2015,16 +2016,16 @@ Following a call to , any operations on th Reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index. A task that represents the asynchronous read operation. The value of the parameter contains the total number of characters read into the buffer. The result value can be less than the number of characters requested if the number of characters currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to read all the characters in a file by using the method. It checks whether each character is a letter, digit, or white space before adding the character to an instance of the class. - + +## Examples + The following example shows how to read all the characters in a file by using the method. It checks whether each character is a letter, digit, or white space before adding the character to an instance of the class. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/example42.cs" id="Snippet42"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/example42.vb" id="Snippet42"::: @@ -2137,13 +2138,13 @@ Following a call to , any operations on th Reads a specified maximum number of characters from the current stream and writes the data to a buffer, beginning at the specified index. The number of characters that have been read. The number will be less than or equal to , depending on whether all input characters have been read. - . - + . + ]]> @@ -2196,6 +2197,7 @@ Following a call to , any operations on th Asynchronously reads the characters from the current stream and writes the data to a buffer. A value task that represents the asynchronous read operation. The value of the type parameter of the value task contains the total number of characters read into the buffer. The result value can be less than the number of characters requested if the number of characters currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2255,11 +2257,11 @@ Following a call to , any operations on th Reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index. A task that represents the asynchronous read operation. The value of the parameter contains the total number of characters read into the buffer. The result value can be less than the number of characters requested if the number of characters currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -2326,26 +2328,26 @@ Following a call to , any operations on th Reads a line of characters from the current stream and returns the data as a string. The next line from the input stream, or if the end of the input stream is reached. - . - - If the current method throws an , the reader's position in the underlying object is advanced by the number of characters the method was able to read, but the characters already read into the internal buffer are discarded. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example reads lines from a file until the end of the file is reached. - + . + + If the current method throws an , the reader's position in the underlying object is advanced by the number of characters the method was able to read, but the characters already read into the internal buffer are discarded. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example reads lines from a file until the end of the file is reached. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/StrmReader ReadLine/CPP/strmreader readline.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/ReadLine/strmreader readline.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader ReadLine/VB/strmreader readline.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader ReadLine/VB/strmreader readline.vb" id="Snippet1"::: + ]]> There is insufficient memory to allocate a buffer for the returned string. @@ -2411,10 +2413,10 @@ Following a call to , any operations on th ## Remarks This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to read the first line of a file by using the method. - + +## Examples + The following example shows how to read the first line of a file by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/example41.cs" id="Snippet41"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/example41.vb" id="Snippet41"::: @@ -2473,6 +2475,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The number of characters in the next line is larger than Int32.MaxValue. The stream reader has been disposed. The reader is currently in use by a previous read operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2527,30 +2530,30 @@ This method stores in the task it returns all non-usage exceptions that the meth Reads all characters from the current position to the end of the stream. The rest of the stream as a string, from the current position to the end. If the current position is at the end of the stream, returns an empty string (""). - . - - works best when you need to read all the input from the current position to the end of the stream. If more control is needed over how many characters are read from the stream, use the method overload, which generally results in better performance. - - assumes that the stream knows when it has reached an end. For interactive protocols in which the server sends data only when you ask for it and does not close the connection, might block indefinitely because it does not reach an end, and should be avoided. - - Note that when using the method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream. If the size of the buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes). - - If the current method throws an , the reader's position in the underlying object is advanced by the number of characters the method was able to read, but the characters already read into the internal buffer are discarded. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example reads all the way to the end of a file in one operation. - + . + + works best when you need to read all the input from the current position to the end of the stream. If more control is needed over how many characters are read from the stream, use the method overload, which generally results in better performance. + + assumes that the stream knows when it has reached an end. For interactive protocols in which the server sends data only when you ask for it and does not close the connection, might block indefinitely because it does not reach an end, and should be avoided. + + Note that when using the method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream. If the size of the buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes). + + If the current method throws an , the reader's position in the underlying object is advanced by the number of characters the method was able to read, but the characters already read into the internal buffer are discarded. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the method; however, this method slows performance and should be called only when absolutely necessary. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example reads all the way to the end of a file in one operation. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/StrmReader ReadToEnd/CPP/strmreader readtoend.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/ReadToEnd/strmreader readtoend.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader ReadToEnd/VB/strmreader readtoend.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/StrmReader ReadToEnd/VB/strmreader readtoend.vb" id="Snippet1"::: + ]]> There is insufficient memory to allocate a buffer for the returned string. @@ -2610,17 +2613,17 @@ This method stores in the task it returns all non-usage exceptions that the meth Reads all characters from the current position to the end of the stream asynchronously and returns them as one string. A task that represents the asynchronous read operation. The value of the parameter contains a string with the characters from the current position to the end of the stream. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to read the contents of a file by using the method. - + +## Examples + The following example shows how to read the contents of a file by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/example40.cs" id="Snippet40"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/example40.vb" id="Snippet40"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/example40.vb" id="Snippet40"::: ]]> @@ -2679,6 +2682,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The number of characters is larger than Int32.MaxValue. The stream reader has been disposed. The reader is currently in use by a previous read operation. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO/StreamWriter.xml b/xml/System.IO/StreamWriter.xml index b36a835ea42..0d5ad59740d 100644 --- a/xml/System.IO/StreamWriter.xml +++ b/xml/System.IO/StreamWriter.xml @@ -68,28 +68,28 @@ Implements a for writing characters to a stream in a particular encoding. - is designed for character output in a particular encoding, whereas classes derived from are designed for byte input and output. - + is designed for character output in a particular encoding, whereas classes derived from are designed for byte input and output. + > [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - - defaults to using an instance of unless specified otherwise. This instance of `UTF8Encoding` is constructed without a byte order mark (BOM), so its method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the property. To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as or . - - By default, a is not thread safe. See for a thread-safe wrapper. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example shows how to use a object to write a file that lists the directories on the C drive, and then uses a object to read and display each directory name. A good practice is to use these objects in a `using` statement so that the unmanaged resources are correctly disposed. The `using` statement automatically calls on the object when the code that is using it has completed. The constructor used in this example is not supported for use in Windows Store Apps. - +> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. + + defaults to using an instance of unless specified otherwise. This instance of `UTF8Encoding` is constructed without a byte order mark (BOM), so its method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the property. To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as or . + + By default, a is not thread safe. See for a thread-safe wrapper. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example shows how to use a object to write a file that lists the directories on the C drive, and then uses a object to read and display each directory name. A good practice is to use these objects in a `using` statement so that the unmanaged resources are correctly disposed. The `using` statement automatically calls on the object when the code that is using it has completed. The constructor used in this example is not supported for use in Windows Store Apps. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/Overview/program.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/streamreadwrite/vb/module1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/streamreadwrite/vb/module1.vb" id="Snippet1"::: + ]]> @@ -164,26 +164,26 @@ The stream to write to. Initializes a new instance of the class for the specified stream by using UTF-8 encoding and the default buffer size. - with UTF-8 encoding without a Byte-Order Mark (BOM), so its method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the property. To specify whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as . The property is initialized using the `stream` parameter. The position of the stream is not reset. - - The object calls on the provided object when is called. - + with UTF-8 encoding without a Byte-Order Mark (BOM), so its method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the property. To specify whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as . The property is initialized using the `stream` parameter. The position of the stream is not reset. + + The object calls on the provided object when is called. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/.ctor/program1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program1.vb" id="Snippet1"::: + ]]> @@ -243,36 +243,36 @@ The complete file path to write to. can be a file name. Initializes a new instance of the class for the specified file by using the default encoding and buffer size. - with UTF-8 encoding without a Byte-Order Mark (BOM), so its method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the property. To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as . - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. If the file exists, it is overwritten; otherwise, a new file is created. - - The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. - + with UTF-8 encoding without a Byte-Order Mark (BOM), so its method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the property. To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as . + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. If the file exists, it is overwritten; otherwise, a new file is created. + + The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/.ctor/program5.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program5.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program5.vb" id="Snippet5"::: + ]]> Access is denied. - is an empty string (""). - - -or- - + is an empty string (""). + + -or- + contains the name of a system device (com1, com2, and so on). is . @@ -339,26 +339,26 @@ The character encoding to use. Initializes a new instance of the class for the specified stream by using the specified encoding and the default buffer size. - property using the encoding parameter, and the property using the stream parameter. The position of the stream is not reset. For additional information, see . - - The object calls on the provided object when is called. - + property using the encoding parameter, and the property using the stream parameter. The position of the stream is not reset. For additional information, see . + + The object calls on the provided object when is called. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example demonstrates this constructor. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/.ctor/program2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program2.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program2.vb" id="Snippet2"::: + ]]> @@ -422,36 +422,36 @@ to append data to the file; to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file. Initializes a new instance of the class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. - with UTF-8 encoding without a Byte-Order Mark (BOM), so its method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the property. To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as . - - The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. - - The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. - + with UTF-8 encoding without a Byte-Order Mark (BOM), so its method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the property. To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as . + + The `path` parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. + + The `path` parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following code example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following code example demonstrates this constructor. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/.ctor/program6.cs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program6.vb" id="Snippet6"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program6.vb" id="Snippet6"::: + ]]> Access is denied. - is empty. - - -or- - + is empty. + + -or- + contains the name of a system device (com1, com2, and so on). is . @@ -564,26 +564,26 @@ The buffer size, in bytes. Initializes a new instance of the class for the specified stream by using the specified encoding and buffer size. - property using the `encoding` parameter, and the property using the `stream` parameter. The position of the stream is not reset. For additional information, see . - - The object calls on the provided object when is called. - + property using the `encoding` parameter, and the property using the `stream` parameter. The position of the stream is not reset. For additional information, see . + + The object calls on the provided object when is called. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example demonstrates this constructor. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/.ctor/program3.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program3.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program3.vb" id="Snippet3"::: + ]]> @@ -651,36 +651,36 @@ The character encoding to use. Initializes a new instance of the class for the specified file by using the specified encoding and default buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. - property using the encoding parameter. For additional information, see . - - `path` can be a file name, including a file on a Universal Naming Convention (UNC) share. - - `path` is not required to be a file stored on disk; it can be any part of a system that supports access via streams. - + property using the encoding parameter. For additional information, see . + + `path` can be a file name, including a file on a Universal Naming Convention (UNC) share. + + `path` is not required to be a file stored on disk; it can be any part of a system that supports access via streams. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example demonstrates this constructor. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/.ctor/program7.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program7.vb" id="Snippet7"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program7.vb" id="Snippet7"::: + ]]> Access is denied. - is empty. - - -or- - + is empty. + + -or- + contains the name of a system device (com1, com2, and so on). is . @@ -793,24 +793,24 @@ to leave the stream open after the object is disposed; otherwise, . Initializes a new instance of the class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open. - object calls on the provided object when is called. - - This constructor initializes the property by using the `encoding` parameter, and initializes the property by using the `stream` parameter. The position of the stream is not reset. For additional information, see the property. - + object calls on the provided object when is called. + + This constructor initializes the property by using the `encoding` parameter, and initializes the property by using the `stream` parameter. The position of the stream is not reset. For additional information, see the property. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - - -## Examples - The following example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + + +## Examples + The following example demonstrates this constructor. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/.ctor/program4.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program4.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program4.vb" id="Snippet4"::: + ]]> @@ -876,35 +876,35 @@ The buffer size, in bytes. Initializes a new instance of the class for the specified file on the specified path, using the specified encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. - property using the encoding parameter. For additional information, see . - - `path` can be a file name, including a file on a Universal Naming Convention (UNC) share. - - `path` is not required to be a file stored on disk; it can be any part of a system that supports access via streams. - + property using the encoding parameter. For additional information, see . + + `path` can be a file name, including a file on a Universal Naming Convention (UNC) share. + + `path` is not required to be a file stored on disk; it can be any part of a system that supports access via streams. + > [!CAUTION] -> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example demonstrates this constructor. - +> When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example demonstrates this constructor. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/.ctor/program8.cs" id="Snippet8"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program8.vb" id="Snippet8"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.streamwriter.ctor/vb/program8.vb" id="Snippet8"::: + ]]> - is an empty string (""). - - -or- - + is an empty string (""). + + -or- + contains the name of a system device (com1, com2, and so on). or is . @@ -968,26 +968,26 @@ to force to flush its buffer; otherwise, . - or . Setting to `true` means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. - - When `AutoFlush` is set to `false`, `StreamWriter` will do a limited amount of buffering, both internally and potentially in the encoder from the encoding you passed in. You can get better performance by setting `AutoFlush` to `false`, assuming that you always call `Close` (or at least `Flush`) when you're done writing with a `StreamWriter`. - - For example, set `AutoFlush` to `true` when you are writing to a device where the user expects immediate feedback. `Console.Out` is one of these cases: The `StreamWriter` used internally for writing to `Console` flushes all its internal state except the encoder state after every call to . - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example shows the syntax for using the `AutoFlush` property. - + or . Setting to `true` means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. + + When `AutoFlush` is set to `false`, `StreamWriter` will do a limited amount of buffering, both internally and potentially in the encoder from the encoding you passed in. You can get better performance by setting `AutoFlush` to `false`, assuming that you always call `Close` (or at least `Flush`) when you're done writing with a `StreamWriter`. + + For example, set `AutoFlush` to `true` when you are writing to a device where the user expects immediate feedback. `Console.Out` is one of these cases: The `StreamWriter` used internally for writing to `Console` flushes all its internal state except the encoder state after every call to . + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example shows the syntax for using the `AutoFlush` property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamWriter/CPP/logger.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/logger.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/logger.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/logger.vb" id="Snippet5"::: + ]]> File and Stream I/O @@ -1040,11 +1040,11 @@ Gets the underlying stream that interfaces with a backing store. The stream this is writing to. - File and Stream I/O @@ -1094,26 +1094,26 @@ Closes the current object and the underlying stream. - . - - This implementation of calls the method passing a `true` value. - - You must call to ensure that all data is correctly written out to the underlying stream. Following a call to , any operations on the might raise exceptions. If there is insufficient space on the disk, calling will raise an exception. - - Flushing the stream will not flush its underlying encoder unless you explicitly call or . Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. - - - -## Examples - The following code example demonstrates the `Close` method. - + . + + This implementation of calls the method passing a `true` value. + + You must call to ensure that all data is correctly written out to the underlying stream. Following a call to , any operations on the might raise exceptions. If there is insufficient space on the disk, calling will raise an exception. + + Flushing the stream will not flush its underlying encoder unless you explicitly call or . Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. + + + +## Examples + The following code example demonstrates the `Close` method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamWriter/CPP/logger.cpp" id="Snippet17"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/logger.cs" id="Snippet17"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/logger.vb" id="Snippet17"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/logger.vb" id="Snippet17"::: + ]]> The current encoding does not support displaying half of a Unicode surrogate pair. @@ -1171,18 +1171,18 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Causes any buffered data to be written to the underlying stream, releases the unmanaged resources used by the , and optionally the managed resources. - references. This method invokes the `Dispose` method of each referenced object. - + references. This method invokes the `Dispose` method of each referenced object. + ]]> The current encoding does not support displaying half of a Unicode surrogate pair. - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed in an earlier call to . - + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed in an earlier call to . + This method calls the dispose method of the base class, . File and Stream I/O @@ -1274,22 +1274,22 @@ Gets the in which the output is written. The specified in the constructor for the current instance, or if an encoding was not specified. - . This allows the XML code to consume an arbitrary and generate the correct XML header. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example retrieves the encoding of the specified instance. - + . This allows the XML code to consume an arbitrary and generate the correct XML header. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example retrieves the encoding of the specified instance. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StreamWriter/CPP/logger.cpp" id="Snippet11"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/logger.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/logger.vb" id="Snippet11"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/logger.vb" id="Snippet11"::: + ]]> File and Stream I/O @@ -1330,7 +1330,7 @@ @@ -1385,15 +1385,15 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream. - . - - Flushing the stream will not flush its underlying encoder unless you explicitly call `Flush` or . Setting to `true` means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . + + Flushing the stream will not flush its underlying encoder unless you explicitly call `Flush` or . Setting to `true` means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The current writer is closed. @@ -1502,24 +1502,24 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo Provides a with no backing store that can be written to, but not read from. - File and Stream I/O @@ -1586,15 +1586,15 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The character to write to the stream. Writes a character to the stream. - . - - The specified character is written to the underlying stream unless the end of the stream is reached prematurely. If is `true`, is invoked automatically. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . + + The specified character is written to the underlying stream unless the end of the stream is reached prematurely. If is `true`, is invoked automatically. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> An I/O error occurs. @@ -1662,17 +1662,17 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo A character array containing the data to write. If is , nothing is written. Writes a character array to the stream. - . - - The specified characters are written to the underlying stream unless the end of the stream is reached prematurely. If is `true`, is invoked automatically. - - This method might provide faster performance than `Write` (`char[],``int,``int`) because it has fewer arguments to check. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . + + The specified characters are written to the underlying stream unless the end of the stream is reached prematurely. If is `true`, is invoked automatically. + + This method might provide faster performance than `Write` (`char[],``int,``int`) because it has fewer arguments to check. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> An I/O error occurs. @@ -1781,17 +1781,17 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The string to write to the stream. If is null, nothing is written. Writes a string to the stream. - . - - The specified is written to the underlying stream unless the end of the stream is reached prematurely. - - is invoked automatically if is `true`. If `value` is `null`, no entries are written. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . + + The specified is written to the underlying stream unless the end of the stream is reached prematurely. + + is invoked automatically if is `true`. If `value` is `null`, no entries are written. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -1983,24 +1983,24 @@ See for a descr The maximum number of characters to write. Writes a subarray of characters to the stream. - . - - The characters are read from `buffer` beginning at `index` and continuing through `index` + (`count` - 1). All characters are written to the underlying stream unless the end of the underlying stream is reached prematurely. is invoked automatically if is `true`. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - This example writes eight characters from a 13-element array to a file, beginning at the third element of the array. - + . + + The characters are read from `buffer` beginning at `index` and continuing through `index` + (`count` - 1). All characters are written to the underlying stream unless the end of the underlying stream is reached prematurely. is invoked automatically if is `true`. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + This example writes eight characters from a 13-element array to a file, beginning at the third element of the array. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_Classic/classic StreamWriter.Write2 Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/Write/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic StreamWriter.Write2 Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic StreamWriter.Write2 Example/VB/source.vb" id="Snippet1"::: + ]]> @@ -2204,15 +2204,15 @@ See , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to write a single character (the letter "a") to a text file by using the method. - + +## Examples + The following example shows how to write a single character (the letter "a") to a text file by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/example20.cs" id="Snippet20"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example20.vb" id="Snippet20"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example20.vb" id="Snippet20"::: ]]> @@ -2279,10 +2279,10 @@ This method stores in the task it returns all non-usage exceptions that the meth ## Remarks This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to write a string to a text file by using the method. - + +## Examples + The following example shows how to write a string to a text file by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/example21.cs" id="Snippet21"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example21.vb" id="Snippet21"::: @@ -2333,6 +2333,7 @@ This method stores in the task it returns all non-usage exceptions that the meth Asynchronously writes a character memory region to the stream. A task that represents the asynchronous write operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2397,10 +2398,10 @@ This method stores in the task it returns all non-usage exceptions that the meth ## Remarks This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to write multiple characters to a text file by using the method. - + +## Examples + The following example shows how to write multiple characters to a text file by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/example24.cs" id="Snippet24"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example24.vb" id="Snippet24"::: @@ -2454,7 +2455,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The character span to write to the stream. Writes the text representation of a character span to the stream, followed by a line terminator. - Asynchronously writes a line terminator to the stream. A task that represents the asynchronous write operation. - property. - + property. + ]]> The stream writer is disposed. @@ -2890,19 +2891,19 @@ See Asynchronously writes a character to the stream, followed by a line terminator. A task that represents the asynchronous write operation. - property. - - - -## Examples - The following example shows how to write a single character (the letter "a") to a line in a text file, followed by another line that contains a single character (the letter "b"), by using the method. - + property. + + + +## Examples + The following example shows how to write a single character (the letter "a") to a line in a text file, followed by another line that contains a single character (the letter "b"), by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/example22.cs" id="Snippet22"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example22.vb" id="Snippet22"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example22.vb" id="Snippet22"::: + ]]> The stream writer is disposed. @@ -2963,16 +2964,16 @@ See Asynchronously writes a string to the stream, followed by a line terminator. A task that represents the asynchronous write operation. - property. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to write two lines that consist of string values to a text file by using the method. - + +## Examples + The following example shows how to write two lines that consist of string values to a text file by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/example23.cs" id="Snippet23"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example23.vb" id="Snippet23"::: @@ -3023,14 +3024,15 @@ See Asynchronously writes the text representation of a character memory region to the stream, followed by a line terminator. A task that represents the asynchronous write operation. - field. - + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -3090,19 +3092,19 @@ The line terminator is defined by the fi Asynchronously writes a subarray of characters to the stream, followed by a line terminator. A task that represents the asynchronous write operation. - property. - - - -## Examples - The following example shows how to write characters to two separate lines in a text file by using the method. The first line contains the first 11 characters from the string (the letters "First line" followed by a space). The second line contains the remaining characters from the string (the letters "and second line"). - + property. + + + +## Examples + The following example shows how to write characters to two separate lines in a text file by using the method. The first line contains the first 11 characters from the string (the letters "First line" followed by a space). The second line contains the remaining characters from the string (the letters "and second line"). + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/example25.cs" id="Snippet25"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example25.vb" id="Snippet25"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example25.vb" id="Snippet25"::: + ]]> diff --git a/xml/System.IO/StringReader.xml b/xml/System.IO/StringReader.xml index 80e2be716a9..524a7aec28f 100644 --- a/xml/System.IO/StringReader.xml +++ b/xml/System.IO/StringReader.xml @@ -68,36 +68,36 @@ Implements a that reads from a string. - enables you to read a string synchronously or asynchronously. You can read a character at a time with the or the method, a line at a time using the or the method and an entire string using the or the method. - + enables you to read a string synchronously or asynchronously. You can read a character at a time with the or the method, a line at a time using the or the method and an entire string using the or the method. + [!INCLUDE[note_unnecessary_dispose](~/includes/note-unnecessary-dispose.md)] - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - The following example shows how to read an entire string asynchronously. - + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + The following example shows how to read an entire string asynchronously. + :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/Overview/example2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringreader/vb/example2.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringreader/vb/example2.vb" id="Snippet2"::: + ]]>
@@ -158,33 +158,33 @@ The string to which the should be initialized. Initializes a new instance of the class that reads from the specified string. -


| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - This code example is part of a larger example provided for the class. - +


| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringReaderWriter/CPP/stringrw.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/.ctor/stringrw.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet2"::: + ]]>
The parameter is . @@ -235,16 +235,16 @@ Closes the . - method. - -This implementation of `Close` calls the , method passing a `true` value. Following a call to `Close`, other methods might throw an exception. - + method. + +This implementation of `Close` calls the , method passing a `true` value. Following a call to `Close`, other methods might throw an exception. + ]]> File and Stream I/O @@ -301,11 +301,11 @@ This implementation of `Close` calls the to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - references. This method invokes the `Dispose` method of each referenced object. - + references. This method invokes the `Dispose` method of each referenced object. + ]]> @@ -369,24 +369,24 @@ This implementation of `Close` calls the Returns the next available character but does not consume it. An integer representing the next character to be read, or -1 if no more characters are available or the stream does not support seeking. - method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a type. - - This method overrides the method. - - The current position of the `StringReader` is not changed by this operation. - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Get the size of a file.|| - + method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a type. + + This method overrides the method. + + The current position of the `StringReader` is not changed by this operation. + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Get the size of a file.|| + ]]> The current reader is closed. @@ -458,35 +458,35 @@ This implementation of `Close` calls the Reads the next character from the input string and advances the character position by one character. The next character from the underlying string, or -1 if no more characters are available. - method. - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - This code example is part of a larger example provided for the class. - + method. + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringReaderWriter/CPP/stringrw.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/.ctor/stringrw.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet3"::: + ]]>
The current reader is closed. @@ -592,28 +592,28 @@ This implementation of `Close` calls the Reads a block of characters from the input string and advances the character position by . The total number of characters read into the buffer. This can be less than the number of characters requested if that many characters are not currently available, or zero if the end of the underlying string has been reached. - . - - The method will read up to `count` characters from the into the `buffer` character array starting at position `index`. Returns the actual number of characters read, or zero if the end of the string has been reached and no characters are read. - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - + . + + The method will read up to `count` characters from the into the `buffer` character array starting at position `index`. Returns the actual number of characters read, or zero if the end of the string has been reached and no characters are read. + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + ]]>
@@ -668,6 +668,7 @@ This implementation of `Close` calls the Asynchronously reads all the characters from the input string, starting at the current position, and advances the current position to the end of the input string. A task that represents the asynchronous read operation. The value of the parameter contains the total number of characters read into the buffer. To be added. + The cancellation token was canceled. This exception is stored into the returned task.
@@ -727,16 +728,16 @@ This implementation of `Close` calls the Reads a specified maximum number of characters from the current string asynchronously and writes the data to a buffer, beginning at the specified index. A task that represents the asynchronous read operation. The value of the parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the string has been reached. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to read the first 23 characters of a string asynchronously. - + +## Examples + The following example shows how to read the first 23 characters of a string asynchronously. + :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/Overview/example1.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringreader/vb/example1.vb" id="Snippet1"::: @@ -851,6 +852,7 @@ This implementation of `Close` calls the + The cancellation token was canceled. This exception is stored into the returned task. @@ -910,11 +912,11 @@ This implementation of `Close` calls the Reads a specified maximum number of characters from the current string asynchronously and writes the data to a buffer, beginning at the specified index. A task that represents the asynchronous read operation. The value of the parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the string has been reached. - @@ -979,39 +981,39 @@ This implementation of `Close` calls the Reads a line of characters from the current string and returns the data as a string. The next line from the current string, or if the end of the string is reached. - method. - - A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), a carriage return immediately followed by a line feed ("\r\n"), or the end-of-stream marker. The string that is returned does not contain the terminating carriage return or line feed. The returned value is `null` if the end-of-stream marker has been reached. That is to say, if there is nothing between the last line read and the end-of-stream marker, the method returns `null`. - - If the current method throws an , the reader's position in the underlying string is advanced by the number of characters the method was able to read, but the characters already read into the internal buffer are discarded. Because the position of the reader in the string cannot be changed, the characters already read are unrecoverable, and can be accessed only by reinitializing the . To avoid such a situation, use the method and store the read characters in a preallocated buffer. - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - This code example is part of a larger example provided for the class. - + method. + + A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), a carriage return immediately followed by a line feed ("\r\n"), or the end-of-stream marker. The string that is returned does not contain the terminating carriage return or line feed. The returned value is `null` if the end-of-stream marker has been reached. That is to say, if there is nothing between the last line read and the end-of-stream marker, the method returns `null`. + + If the current method throws an , the reader's position in the underlying string is advanced by the number of characters the method was able to read, but the characters already read into the internal buffer are discarded. Because the position of the reader in the string cannot be changed, the characters already read are unrecoverable, and can be accessed only by reinitializing the . To avoid such a situation, use the method and store the read characters in a preallocated buffer. + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringReaderWriter/CPP/stringrw.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/.ctor/stringrw.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet2"::: + ]]>
The current reader is closed. @@ -1077,10 +1079,10 @@ This implementation of `Close` calls the , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to read one line at a time from a string asynchronously. - + +## Examples + The following example shows how to read one line at a time from a string asynchronously. + :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/Overview/example3.cs" id="Snippet3"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringreader/vb/example3.vb" id="Snippet3"::: @@ -1129,6 +1131,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The number of characters in the next line is larger than Int32.MaxValue. The string reader has been disposed. The reader is currently in use by a previous read operation. + The cancellation token was canceled. This exception is stored into the returned task.
@@ -1177,37 +1180,37 @@ This method stores in the task it returns all non-usage exceptions that the meth Reads all characters from the current position to the end of the string and returns them as a single string. The content from the current position to the end of the underlying string. - method. - - If the current method throws an , the reader's position in the underlying string is advanced by the number of characters the method was able to read, but the characters already read into the internal buffer are discarded. Because the position of the reader in the string cannot be changed, the characters already read are unrecoverable, and can be accessed only by reinitializing the . To avoid such a situation, use the method and store the read characters in a preallocated buffer. - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - This code example is part of a larger example provided for the class. - + method. + + If the current method throws an , the reader's position in the underlying string is advanced by the number of characters the method was able to read, but the characters already read into the internal buffer are discarded. Because the position of the reader in the string cannot be changed, the characters already read are unrecoverable, and can be accessed only by reinitializing the . To avoid such a situation, use the method and store the read characters in a preallocated buffer. + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.TextReaderWriter/CPP/textrw.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/ReadToEnd/textrw.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.TextReaderWriter/VB/textrw.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.TextReaderWriter/VB/textrw.vb" id="Snippet5"::: + ]]>
There is insufficient memory to allocate a buffer for the returned string. @@ -1272,10 +1275,10 @@ This method stores in the task it returns all non-usage exceptions that the meth ## Remarks This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to read an entire string asynchronously. - + +## Examples + The following example shows how to read an entire string asynchronously. + :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/Overview/example2.cs" id="Snippet2"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringreader/vb/example2.vb" id="Snippet2"::: @@ -1324,6 +1327,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The number of characters is larger than Int32.MaxValue. The string reader has been disposed. The reader is currently in use by a previous read operation. + The cancellation token was canceled. This exception is stored into the returned task.
diff --git a/xml/System.IO/StringWriter.xml b/xml/System.IO/StringWriter.xml index 59104be8e91..a52b4d81a4b 100644 --- a/xml/System.IO/StringWriter.xml +++ b/xml/System.IO/StringWriter.xml @@ -68,37 +68,37 @@ Implements a for writing information to a string. The information is stored in an underlying . - enables you to write to a string synchronously or asynchronously. You can write a character at a time with the or the method, a string at a time using the or the method. In addition, you can write a character, an array of characters or a string followed by the line terminator asynchronously with one of the methods. - + enables you to write to a string synchronously or asynchronously. You can write a character at a time with the or the method, a string at a time using the or the method. In addition, you can write a character, an array of characters or a string followed by the line terminator asynchronously with one of the methods. + [!INCLUDE[note_unnecessary_dispose](~/includes/note-unnecessary-dispose.md)] - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - The following code example demonstrates the creation of a continuous paragraph from a group of double-spaced sentences, and then the conversion of the paragraph back to the original text. - + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + The following code example demonstrates the creation of a continuous paragraph from a group of double-spaced sentences, and then the conversion of the paragraph back to the original text. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringReaderWriter/CPP/stringrw.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/.ctor/stringrw.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet1"::: + ]]>
@@ -166,35 +166,35 @@ Initializes a new instance of the class. - object is automatically created and associated with the new instance of the class. Since a format control is not specified for this constructor, the new instance will be initialized with . - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - The following code example demonstrates how to construct a string using the `StringWriter` class. - + object is automatically created and associated with the new instance of the class. Since a format control is not specified for this constructor, the new instance will be initialized with . + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + The following code example demonstrates how to construct a string using the `StringWriter` class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringWriter1/CPP/strwriter1.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/.ctor/strwriter1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet1"::: + ]]>
File and Stream I/O @@ -254,35 +254,35 @@ An object that controls formatting. Initializes a new instance of the class with the specified format control. - object is automatically created and associated with the new instance of the class. - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - The following code example demonstrates how to construct a string in a specific culture. - + object is automatically created and associated with the new instance of the class. + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + The following code example demonstrates how to construct a string in a specific culture. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringWriter2/CPP/strwriter2.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/.ctor/strwriter2.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter2/VB/strwriter2.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter2/VB/strwriter2.vb" id="Snippet1"::: + ]]>
File and Stream I/O @@ -341,35 +341,35 @@ The object to write to. Initializes a new instance of the class that writes to the specified . - . - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - The following code example demonstrates using the class to modify the underlying string in a closed `StringWriter`. - + . + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + The following code example demonstrates using the class to modify the underlying string in a closed `StringWriter`. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringWriter3/CPP/strwriter3.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/.ctor/strwriter3.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter3/VB/strwriter3.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter3/VB/strwriter3.vb" id="Snippet1"::: + ]]>
@@ -427,24 +427,24 @@ An object that controls formatting. Initializes a new instance of the class that writes to the specified and has the specified format provider. -


| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - +


| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + ]]>
@@ -502,26 +502,26 @@ Closes the current and the underlying stream. - . - - This implementation of `Close` calls the method passing a `true` value. - - Flushing the stream will not flush its underlying encoder unless you explicitly call `Close`. Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. - - - -## Examples - This code example is part of a larger example provided for the constructor. - + . + + This implementation of `Close` calls the method passing a `true` value. + + Flushing the stream will not flush its underlying encoder unless you explicitly call `Close`. Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. + + + +## Examples + This code example is part of a larger example provided for the constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringWriter3/CPP/strwriter3.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/.ctor/strwriter3.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter3/VB/strwriter3.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter3/VB/strwriter3.vb" id="Snippet2"::: + ]]> File and Stream I/O @@ -584,11 +584,11 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - references. This method invokes the `Dispose` method of each referenced object. - + references. This method invokes the `Dispose` method of each referenced object. + ]]> @@ -651,28 +651,28 @@ Gets the in which the output is written. The in which the output is written. - constructor. - + constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringWriter1/CPP/strwriter1.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/.ctor/strwriter1.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet4"::: + ]]> File and Stream I/O @@ -778,28 +778,28 @@ Returns the underlying . The underlying . - constructor. - + constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringWriter1/CPP/strwriter1.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/.ctor/strwriter1.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet3"::: + ]]> File and Stream I/O @@ -859,26 +859,26 @@ Returns a string containing the characters written to the current so far. The string containing the characters written to the current . - constructor. - + constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringWriter2/CPP/strwriter2.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/.ctor/strwriter2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter2/VB/strwriter2.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter2/VB/strwriter2.vb" id="Snippet2"::: + ]]> File and Stream I/O @@ -951,35 +951,35 @@ The character to write. Writes a character to the string. - . - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - This code example is part of a larger example provided for the constructor. - + . + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + This code example is part of a larger example provided for the constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringWriter1/CPP/strwriter1.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/.ctor/strwriter1.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet2"::: + ]]>
The writer is closed. @@ -1084,37 +1084,37 @@ The string to write. Writes a string to the current string. - . - - If the specified string is `null`, nothing is written. - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - This code example is part of a larger example provided for the class. - + . + + If the specified string is `null`, nothing is written. + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + This code example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringReaderWriter/CPP/stringrw.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringReader/.ctor/stringrw.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringReaderWriter/VB/stringrw.vb" id="Snippet3"::: + ]]>
The writer is closed. @@ -1215,37 +1215,37 @@ The maximum number of characters to write. Writes a subarray of characters to the string. - . - - This method writes `count` characters of data to this `StringWriter` from `buffer`, starting at position `index`. - - The following table lists examples of other typical or related I/O tasks. - -|To do this...|See the example in this topic...| -|-------------------|--------------------------------------| -|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| -|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| -|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| -|Get the size of a file.|| -|Get the attributes of a file.|| -|Set the attributes of a file.|| -|Determine if a file exists.|| -|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| -|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| - - - -## Examples - This code example is part of a larger example provided for the constructor. - + . + + This method writes `count` characters of data to this `StringWriter` from `buffer`, starting at position `index`. + + The following table lists examples of other typical or related I/O tasks. + +|To do this...|See the example in this topic...| +|-------------------|--------------------------------------| +|Create a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Write to a text file.|[How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file)| +|Read from a text file.|[How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file)| +|Append text to a file.|[How to: Open and Append to a Log File](/dotnet/standard/io/how-to-open-and-append-to-a-log-file)



| +|Get the size of a file.|| +|Get the attributes of a file.|| +|Set the attributes of a file.|| +|Determine if a file exists.|| +|Read from a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| +|Write to a binary file.|[How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file)| + + + +## Examples + This code example is part of a larger example provided for the constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.StringWriter1/CPP/strwriter1.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/.ctor/strwriter1.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StringWriter1/VB/strwriter1.vb" id="Snippet2"::: + ]]>
@@ -1328,10 +1328,10 @@ ## Remarks This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to write characters by using the method. - + +## Examples + The following example shows how to write characters by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/WriteAsync/example5.cs" id="Snippet5"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringwriter/vb/example5.vb" id="Snippet5"::: @@ -1400,10 +1400,10 @@ This method stores in the task it returns all non-usage exceptions that the meth ## Remarks This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to write a string by using the method. - + +## Examples + The following example shows how to write a string by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/WriteAsync/example4.cs" id="Snippet4"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringwriter/vb/example4.vb" id="Snippet4"::: @@ -1454,6 +1454,7 @@ This method stores in the task it returns all non-usage exceptions that the meth Asynchronously writes a memory region of characters to the string. A task that represents the asynchronous write operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task.
@@ -1496,6 +1497,7 @@ This method stores in the task it returns all non-usage exceptions that the meth Asynchronously writes the text representation of a string builder to the string. A task that represents the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task.
@@ -1560,10 +1562,10 @@ This method stores in the task it returns all non-usage exceptions that the meth ## Remarks This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - -## Examples - The following example shows how to write characters by using the method. - + +## Examples + The following example shows how to write characters by using the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/WriteAsync/example6.cs" id="Snippet6"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringwriter/vb/example6.vb" id="Snippet6"::: @@ -1855,6 +1857,7 @@ The following example shows how to write a string by using the Asynchronously writes the string representation of the memory region of characters to the current string, followed by a line terminator. A task that represents the asynchronous write operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task.
@@ -1897,6 +1900,7 @@ The following example shows how to write a string by using the Asynchronously writes the string representation of the string builder to the current string, followed by a line terminator. A task that represents the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1967,7 +1971,7 @@ The line terminator is defined by the pro The following example shows how to write characters by using the method. :::code language="csharp" source="~/snippets/csharp/System.IO/StringWriter/WriteAsync/example3.cs" id="Snippet3"::: -:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringwriter/vb/example3.vb" id="Snippet3"::: +:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.stringwriter/vb/example3.vb" id="Snippet3"::: ]]> diff --git a/xml/System.IO/TextReader.xml b/xml/System.IO/TextReader.xml index 8ec9f884c13..7bb1bb0c0b5 100644 --- a/xml/System.IO/TextReader.xml +++ b/xml/System.IO/TextReader.xml @@ -78,22 +78,22 @@ Represents a reader that can read a sequential series of characters. - is the abstract base class of and , which read characters from streams and strings, respectively. Use these derived classes to open a text file for reading a specified range of characters, or to create a reader based on an existing stream. - + is the abstract base class of and , which read characters from streams and strings, respectively. Use these derived classes to open a text file for reading a specified range of characters, or to create a reader based on an existing stream. + > [!IMPORTANT] -> This type implements the interface. When you have finished using any type that derives from this type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see Dispose and the "Using an Object that Implements IDisposable" section in the interface topic. - - - -## Examples - The class is an abstract class. Therefore, you do not instantiate it in your code. The class derives from and provides implementations of the members for reading from a stream. The following example shows how to read all the characters in a file by using the method. It checks whether each character is a letter, digit, or white space before adding the character to an instance of the class. - +> This type implements the interface. When you have finished using any type that derives from this type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see Dispose and the "Using an Object that Implements IDisposable" section in the interface topic. + + + +## Examples + The class is an abstract class. Therefore, you do not instantiate it in your code. The class derives from and provides implementations of the members for reading from a stream. The following example shows how to read all the characters in a file by using the method. It checks whether each character is a letter, digit, or white space before adding the character to an instance of the class. + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamReader/Overview/example42.cs" id="Snippet42"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/example42.vb" id="Snippet42"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamReader/VB/example42.vb" id="Snippet42"::: + ]]> @@ -148,11 +148,11 @@ Initializes a new instance of the class. - @@ -204,14 +204,14 @@ Closes the and releases any system resources associated with the . - method and passes it a `true` value. - + method and passes it a `true` value. + > [!NOTE] -> In derived classes, do not override the method. Instead, override the method to add code for releasing resources. - +> In derived classes, do not override the method. Instead, override the method to add code for releasing resources. + ]]> @@ -279,16 +279,16 @@ Releases all resources used by the object. - when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. - - For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + + For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + > [!NOTE] -> Always call before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's method. - +> Always call before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's method. + ]]> @@ -342,19 +342,19 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose` method of each referenced object. - + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose` method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding this method, be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement this method, see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding this method, be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement this method, see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). File and Stream I/O @@ -406,19 +406,19 @@ Provides a with no data to read from. - text reader is similar to reading from the end of a stream: - -- The and methods return -1. - -- The method returns zero. - -- The method returns `null`. - -- The method returns an empty string. - + text reader is similar to reading from the end of a stream: + +- The and methods return -1. + +- The method returns zero. + +- The method returns `null`. + +- The method returns an empty string. + ]]> @@ -474,15 +474,15 @@ Reads the next character without changing the state of the reader or the character source. Returns the next available character without actually reading it from the reader. An integer representing the next character to be read, or -1 if no more characters are available or the reader does not support seeking. - method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a type. - - The current position of the is not changed by this operation. The returned value is -1 if no more characters are available. The default implementation returns -1. - - The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a type. + + The current position of the is not changed by this operation. The returned value is -1 if no more characters are available. The default implementation returns -1. + + The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + ]]> The is closed. @@ -551,11 +551,11 @@ Reads the next character from the text reader and advances the character position by one character. The next character from the text reader, or -1 if no more characters are available. The default implementation returns -1. - class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + ]]> The is closed. @@ -666,13 +666,13 @@ Reads a specified maximum number of characters from the current reader and writes the data to a buffer, beginning at the specified index. The number of characters that have been read. The number will be less than or equal to , depending on whether the data is available within the reader. This method returns 0 (zero) if it is called when no more characters are left to read. - is a blocking version of this method. - - The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + is a blocking version of this method. + + The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + ]]> @@ -730,6 +730,7 @@ Asynchronously reads the characters from the current stream into a memory block. A value task that represents the asynchronous read operation. The value of the type parameter contains the number of characters that have been read, or 0 if at the end of the stream and no data was read. The number will be less than or equal to the length, depending on whether the data is available within the stream. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -789,13 +790,13 @@ Reads a specified maximum number of characters from the current text reader asynchronously and writes the data to a buffer, beginning at the specified index. A task that represents the asynchronous read operation. The value of the parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the text has been reached. - class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -914,13 +915,13 @@ Reads a specified maximum number of characters from the current text reader and writes the data to a buffer, beginning at the specified index. The number of characters that have been read. The number will be less than or equal to , depending on whether all input characters have been read. - . - + . + ]]> @@ -977,6 +978,7 @@ Asynchronously reads the characters from the current stream and writes the data to a buffer. A value task that represents the asynchronous read operation. The value of the type parameter contains the total number of characters read into the buffer. The result value can be less than the number of characters requested if the number of characters currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1036,11 +1038,11 @@ Reads a specified maximum number of characters from the current text reader asynchronously and writes the data to a buffer, beginning at the specified index. A task that represents the asynchronous read operation. The value of the parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the text has been reached. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1106,17 +1108,17 @@ Reads a line of characters from the text reader and returns the data as a string. The next line from the reader, or if all characters have been read. - , or the end-of-stream marker. The string that is returned does not contain the terminating carriage return or line feed. The return value is `null` if the end of the input stream has been reached. - - If the method throws an exception, the reader's position in the underlying is advanced by the number of characters the method was able to read, but the characters that were already read into the internal buffer are discarded. Because the position of the reader in the stream cannot be changed, the characters that were already read are unrecoverable and can be accessed only by reinitializing the object. If the initial position within the stream is unknown or the stream does not support seeking, the underlying also needs to be reinitialized. - - To avoid such a situation and produce robust code you should use the method and store the read characters in a preallocated buffer. - - The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + , or the end-of-stream marker. The string that is returned does not contain the terminating carriage return or line feed. The return value is `null` if the end of the input stream has been reached. + + If the method throws an exception, the reader's position in the underlying is advanced by the number of characters the method was able to read, but the characters that were already read into the internal buffer are discarded. Because the position of the reader in the stream cannot be changed, the characters that were already read are unrecoverable and can be accessed only by reinitializing the object. If the initial position within the stream is unknown or the stream does not support seeking, the underlying also needs to be reinitialized. + + To avoid such a situation and produce robust code you should use the method and store the read characters in a preallocated buffer. + + The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + ]]> An I/O error occurs. @@ -1181,13 +1183,13 @@ Reads a line of characters asynchronously and returns the data as a string. A task that represents the asynchronous read operation. The value of the parameter contains the next line from the text reader, or is if all of the characters have been read. - class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - - If the current represents the standard input stream returned by the property, the method executes synchronously rather than asynchronously. - + class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + + If the current represents the standard input stream returned by the property, the method executes synchronously rather than asynchronously. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1256,6 +1258,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The number of characters in the next line is larger than Int32.MaxValue. The text reader has been disposed. The reader is currently in use by a previous read operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1304,15 +1307,15 @@ This method stores in the task it returns all non-usage exceptions that the meth Reads all characters from the current position to the end of the text reader and returns them as one string. A string that contains all characters from the current position to the end of the text reader. - exception, the reader's position in the underlying is advanced by the number of characters the method was able to read, but the characters that were already read into the internal buffer are discarded. Because the position of the reader in the stream cannot be changed, the characters that were already read are unrecoverable and can be accessed only by reinitializing the . If the initial position within the stream is unknown or the stream does not support seeking, the underlying also needs to be reinitialized. - - To avoid such a situation and produce robust code you should use the method and store the read characters in a preallocated buffer. - - The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + exception, the reader's position in the underlying is advanced by the number of characters the method was able to read, but the characters that were already read into the internal buffer are discarded. Because the position of the reader in the stream cannot be changed, the characters that were already read are unrecoverable and can be accessed only by reinitializing the . If the initial position within the stream is unknown or the stream does not support seeking, the underlying also needs to be reinitialized. + + To avoid such a situation and produce robust code you should use the method and store the read characters in a preallocated buffer. + + The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + ]]> An I/O error occurs. @@ -1380,11 +1383,11 @@ This method stores in the task it returns all non-usage exceptions that the meth Reads all characters from the current position to the end of the text reader asynchronously and returns them as one string. A task that represents the asynchronous read operation. The value of the parameter contains a string with the characters from the current position to the end of the text reader. - class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1449,6 +1452,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The number of characters is larger than Int32.MaxValue. The text reader has been disposed. The reader is currently in use by a previous read operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1497,11 +1501,11 @@ This method stores in the task it returns all non-usage exceptions that the meth Creates a thread-safe wrapper around the specified . A thread-safe . - instance and restricts access to it by multiple threads. All reads from the returned wrapper will be thread safe. - + instance and restricts access to it by multiple threads. All reads from the returned wrapper will be thread safe. + ]]> @@ -1547,7 +1551,7 @@ This method stores in the task it returns all non-usage exceptions that the meth instance is cast to an interface. ]]> diff --git a/xml/System.IO/TextWriter.xml b/xml/System.IO/TextWriter.xml index d94a4ca4692..e407024b267 100644 --- a/xml/System.IO/TextWriter.xml +++ b/xml/System.IO/TextWriter.xml @@ -86,26 +86,26 @@ Represents a writer that can write a sequential series of characters. This class is abstract. - is the abstract base class of and , which write characters to streams and strings, respectively. Create an instance of to write an object to a string, write strings to a file, or to serialize XML. You can also use an instance of to write text to a custom backing store using the same APIs you would use for a string or a stream, or to add support for text formatting. - - All the `Write` methods of having primitive data types as parameters write out the values as strings. - - By default, a is not thread safe. See for a thread-safe wrapper. - + is the abstract base class of and , which write characters to streams and strings, respectively. Create an instance of to write an object to a string, write strings to a file, or to serialize XML. You can also use an instance of to write text to a custom backing store using the same APIs you would use for a string or a stream, or to add support for text formatting. + + All the `Write` methods of having primitive data types as parameters write out the values as strings. + + By default, a is not thread safe. See for a thread-safe wrapper. + > [!IMPORTANT] -> This type implements the interface. When you have finished using any type that derives from this type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see Dispose and the "Using an Object that Implements IDisposable" section in the interface topic. - +> This type implements the interface. When you have finished using any type that derives from this type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see Dispose and the "Using an Object that Implements IDisposable" section in the interface topic. + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - -## Examples + +## Examples The class is an abstract class. Therefore, you do not instantiate it in your code. The class derives from and provides implementations of the members for writing to a stream. The following example shows how to write two lines that consist of string values to a text file by using the method. - + :::code language="csharp" source="~/snippets/csharp/System.IO/StreamWriter/AutoFlush/example23.cs" id="Snippet23"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example23.vb" id="Snippet23"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.StreamWriter/VB/example23.vb" id="Snippet23"::: + ]]> @@ -171,15 +171,15 @@ Initializes a new instance of the class. - property. When the property is `null`, the culture of the current thread is used for formatting. - - Use this constructor for derived classes. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + property. When the property is `null`, the culture of the current thread is used for formatting. + + Use this constructor for derived classes. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -236,13 +236,13 @@ An object that controls formatting. Initializes a new instance of the class with the specified format provider. - property. The value of the property specifies the culture-specific formatting that is used when you call the and methods. If you do not want to provide a format provider, you create an instance by using the constructor, which sets the property to `null`. When the property is `null`, the culture of the current thread is used for formatting. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + property. The value of the property specifies the culture-specific formatting that is used when you call the and methods. If you do not want to provide a format provider, you create an instance by using the constructor, which sets the property to `null`. When the property is `null`, the culture of the current thread is used for formatting. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -295,16 +295,16 @@ Closes the current writer and releases any system resources associated with the writer. - method and passes it a `true` value. - - Flushing the stream will not flush its underlying encoder unless you explicitly call or `Close`. Setting the property to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can be encoded only after the encoder receives the adjacent character or characters. - + method and passes it a `true` value. + + Flushing the stream will not flush its underlying encoder unless you explicitly call or `Close`. Setting the property to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can be encoded only after the encoder receives the adjacent character or characters. + > [!NOTE] -> In derived classes, do not override the method. Instead, override the method to add code for releasing resources. - +> In derived classes, do not override the method. Instead, override the method to add code for releasing resources. + ]]> File and Stream I/O @@ -356,11 +356,11 @@ Stores the newline characters used for this . - @@ -428,15 +428,15 @@ Releases all resources used by the object. - when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. - - For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - - **Note** Always call before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's method. - + when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + + For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + + **Note** Always call before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's method. + ]]> @@ -490,19 +490,19 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - . By default, this method specifies the `disposing` parameter as `true`. `Finalize` specifies the `disposing` parameter as `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose` method of each referenced object. - + . By default, this method specifies the `disposing` parameter as `true`. `Finalize` specifies the `disposing` parameter as `false`. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose` method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding this method, be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement this method, see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding this method, be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement this method, see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). File and Stream I/O @@ -597,13 +597,13 @@ When overridden in a derived class, returns the character encoding in which the output is written. The character encoding in which the output is written. - @@ -658,13 +658,13 @@ Clears all buffers for the current writer and causes any buffered data to be written to the underlying device. - . Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. - + . Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. + ]]> @@ -775,15 +775,15 @@ Gets an object that controls formatting. An object for a specific culture, or the formatting of the current culture if no other culture is specified. - property specifies the culture-specific formatting that is used when you call the and methods. If you do not want to provide a format provider, you create an instance by using the constructor, which sets the property to `null`. When the property contains `null`, the culture of the current thread is used for formatting. - - For an example of creating a file and writing text to a file, see [How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file). For an example of reading text from a file, see [How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file). For an example of reading from and writing to a binary file, see [How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file). - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + property specifies the culture-specific formatting that is used when you call the and methods. If you do not want to provide a format provider, you create an instance by using the constructor, which sets the property to `null`. When the property contains `null`, the culture of the current thread is used for formatting. + + For an example of creating a file and writing text to a file, see [How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file). For an example of reading text from a file, see [How to: Read Text from a File](/dotnet/standard/io/how-to-read-text-from-a-file). For an example of reading from and writing to a binary file, see [How to: Read and Write to a Newly Created Data File](/dotnet/standard/io/how-to-read-and-write-to-a-newly-created-data-file). + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -844,16 +844,16 @@ Gets or sets the line terminator string used by the current . The line terminator string for the current . - , only "\n" or "\r\n" should be used as terminator strings. If `NewLine` is set to `null`, the default newline character is used instead. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + , only "\n" or "\r\n" should be used as terminator strings. If `NewLine` is set to `null`, the default newline character is used instead. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -907,15 +907,15 @@ For non-Unix platforms, the default line terminator string is a carriage return Provides a with no backing store that can be written to, but not read from. - methods are invoked on `Null`, the call simply returns, and no data is actually written to any backing store. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + methods are invoked on `Null`, the call simply returns, and no data is actually written to any backing store. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -977,13 +977,13 @@ For non-Unix platforms, the default line terminator string is a carriage return Creates a thread-safe wrapper around the specified . A thread-safe wrapper. - instance that is returned. For more information about synchronization and threading, see [Synchronizing Data for Multithreading](/dotnet/standard/threading/synchronizing-data-for-multithreading). - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + instance that is returned. For more information about synchronization and threading, see [Synchronizing Data for Multithreading](/dotnet/standard/threading/synchronizing-data-for-multithreading). + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -1029,7 +1029,7 @@ For non-Unix platforms, the default line terminator string is a carriage return instance is cast to an interface. ]]> @@ -1095,15 +1095,15 @@ This member is an explicit interface member implementation. It can be used only The value to write. Writes the text representation of a value to the text stream. - method. - - This method outputs either or . - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. + + This method outputs either or . + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -1167,13 +1167,13 @@ This member is an explicit interface member implementation. It can be used only The character to write to the text stream. Writes a character to the text stream. - The is closed. @@ -1234,15 +1234,15 @@ This member is an explicit interface member implementation. It can be used only The character array to write to the text stream. Writes a character array to the text stream. - . - - This default method calls the method and passes the entire character array. If the character array is `null`, nothing is written. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . + + This default method calls the method and passes the entire character array. If the character array is `null`, nothing is written. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -1301,11 +1301,11 @@ This member is an explicit interface member implementation. It can be used only The decimal value to write. Writes the text representation of a decimal value to the text stream. - property, if not `null`, specifies the culture-specific formatting. - + property, if not `null`, specifies the culture-specific formatting. + ]]> The is closed. @@ -1366,13 +1366,13 @@ This member is an explicit interface member implementation. It can be used only The 8-byte floating-point value to write. Writes the text representation of an 8-byte floating-point value to the text stream. - method. The property, if not `null`, specifies the culture-specific formatting. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. The property, if not `null`, specifies the culture-specific formatting. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -1433,13 +1433,13 @@ This member is an explicit interface member implementation. It can be used only The 4-byte signed integer to write. Writes the text representation of a 4-byte signed integer to the text stream. - method. The property, if not `null`, specifies the culture-specific formatting. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. The property, if not `null`, specifies the culture-specific formatting. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -1500,15 +1500,15 @@ This member is an explicit interface member implementation. It can be used only The 8-byte signed integer to write. Writes the text representation of an 8-byte signed integer to the text stream. - method. The property, if not `null`, specifies the culture-specific formatting. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - [How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file) - + method. The property, if not `null`, specifies the culture-specific formatting. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + [How to: Write Text to a File](/dotnet/standard/io/how-to-write-text-to-a-file) + ]]> The is closed. @@ -1567,15 +1567,15 @@ This member is an explicit interface member implementation. It can be used only The object to write. Writes the text representation of an object to the text stream by calling the method on that object. - overload. - - If the specified object is `null`, no action is taken and no exception is thrown. Otherwise, the object's `ToString` method is called to produce the string representation, and the resulting string is then written to the output stream. The property, if not `null`, specifies the culture-specific formatting. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + overload. + + If the specified object is `null`, no action is taken and no exception is thrown. Otherwise, the object's `ToString` method is called to produce the string representation, and the resulting string is then written to the output stream. The property, if not `null`, specifies the culture-specific formatting. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -1687,13 +1687,13 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The 4-byte floating-point value to write. Writes the text representation of a 4-byte floating-point value to the text stream. - method. The property, if not `null`, specifies the culture-specific formatting. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. The property, if not `null`, specifies the culture-specific formatting. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -1755,17 +1755,17 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The string to write. Writes a string to the text stream. - overload. - - This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . - - If `value` is `null`, nothing is written to the text stream. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + overload. + + This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . + + If `value` is `null`, nothing is written to the text stream. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -1879,13 +1879,13 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The 4-byte unsigned integer to write. Writes the text representation of a 4-byte unsigned integer to the text stream. - method. The property, if not `null`, specifies the culture-specific formatting. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. The property, if not `null`, specifies the culture-specific formatting. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -1952,13 +1952,13 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The 8-byte unsigned integer to write. Writes the text representation of an 8-byte unsigned integer to the text stream. - method. The property, if not `null`, specifies the culture-specific formatting. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. The property, if not `null`, specifies the culture-specific formatting. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -2028,43 +2028,43 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The object to format and write. Writes a formatted string to the text stream, using the same semantics as the method. - . Because this overload has only a single object in its parameter list, the value of *index* must always be 0. If there is no parameter in the *index* position, a is thrown.| -|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| -|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| - - The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". - - This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . - - If a specified object is not referenced in the format string, it is ignored. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . Because this overload has only a single object in its parameter list, the value of *index* must always be 0. If there is no parameter in the *index* position, a is thrown.| +|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| +|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| + + The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". + + This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . + + If a specified object is not referenced in the format string, it is ignored. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -2072,10 +2072,10 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The is closed. An I/O error occurs. - is not a valid composite format string. - - -or- - + is not a valid composite format string. + + -or- + The index of a format item is less than 0 (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is one). @@ -2150,43 +2150,43 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the An object array that contains zero or more objects to format and write. Writes a formatted string to the text stream, using the same semantics as the method. - . Because this overload has an array in its parameter list, the value of *index* must always be less than the length of the array. If there is no parameter in the *index* position, a is thrown.| -|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| -|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| - - The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". - - This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . - - If a specified object is not referenced in the format string, it is ignored. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . Because this overload has an array in its parameter list, the value of *index* must always be less than the length of the array. If there is no parameter in the *index* position, a is thrown.| +|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| +|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| + + The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". + + This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . + + If a specified object is not referenced in the format string, it is ignored. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -2194,10 +2194,10 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The is closed. An I/O error occurs. - is not a valid composite format string. - - -or- - + is not a valid composite format string. + + -or- + The index of a format item is less than 0 (zero), or greater than or equal to the length of the array. @@ -2259,15 +2259,15 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The number of characters to write. Writes a subarray of characters to the text stream. - overload for each character in `buffer` between `index` and (`index` + `count`). - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + overload for each character in `buffer` between `index` and (`index` + `count`). + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The buffer length minus is less than . @@ -2342,43 +2342,43 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The second object to format and write. Writes a formatted string to the text stream using the same semantics as the method. - . Because this overload has two objects in its parameter list, the value of *index* must always be 0 or 1. If there is no parameter in the *index* position, a is thrown.| -|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| -|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| - - The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". - - This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . - - If a specified object is not referenced in the format string, it is ignored. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . Because this overload has two objects in its parameter list, the value of *index* must always be 0 or 1. If there is no parameter in the *index* position, a is thrown.| +|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| +|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| + + The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". + + This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . + + If a specified object is not referenced in the format string, it is ignored. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -2386,10 +2386,10 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The is closed. An I/O error occurs. - is not a valid composite format string. - - -or- - + is not a valid composite format string. + + -or- + The index of a format item is less than 0 (zero) or greater than or equal to the number of objects to be formatted (which, for this method overload, is two). @@ -2460,43 +2460,43 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The third object to format and write. Writes a formatted string to the text stream, using the same semantics as the method. - . Because this overload has three objects in its parameter list, the value of *index* must always be 0, 1, or 2. If there is no parameter in the *index* position, a is thrown.| -|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| -|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| - - The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". - - This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . - - If a specified object is not referenced in the format string, it is ignored. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . Because this overload has three objects in its parameter list, the value of *index* must always be 0, 1, or 2. If there is no parameter in the *index* position, a is thrown.| +|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| +|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| + + The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". + + This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . + + If a specified object is not referenced in the format string, it is ignored. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -2504,10 +2504,10 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the The is closed. An I/O error occurs. - is not a valid composite format string. - - -or- - + is not a valid composite format string. + + -or- + The index of a format item is less than 0 (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is three). @@ -2581,11 +2581,11 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the Writes a character to the text stream asynchronously. A task that represents the asynchronous write operation. - class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -2710,11 +2710,11 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the Writes a string to the text stream asynchronously. A task that represents the asynchronous write operation. - class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -2766,6 +2766,7 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the Asynchronously writes a character memory region to the text stream. A task that represents the asynchronous write operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2810,7 +2811,7 @@ This method is equivalent to `Write(stringBuilder.ToString())`, but it uses the method to avoid creating the intermediate string. @@ -2818,6 +2819,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -2877,11 +2879,11 @@ This method stores in the task it returns all non-usage exceptions that the meth Writes a subarray of characters to the text stream asynchronously. A task that represents the asynchronous write operation. - class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -3020,17 +3022,17 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The value to write. Writes the text representation of a value to the text stream, followed by a line terminator. - method. - - This method outputs either or . - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. + + This method outputs either or . + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -3090,15 +3092,15 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The character to write to the text stream. Writes a character to the text stream, followed by a line terminator. - followed by . - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + followed by . + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -3159,17 +3161,17 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The character array from which data is read. Writes an array of characters to the text stream, followed by a line terminator. - followed by . - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + followed by . + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -3229,13 +3231,13 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The decimal value to write. Writes the text representation of a decimal value to the text stream, followed by a line terminator. - property, if not `null`, specifies the culture-specific formatting. For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - The line terminator is defined by the field. - + property, if not `null`, specifies the culture-specific formatting. For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + The line terminator is defined by the field. + ]]> The is closed. @@ -3296,13 +3298,13 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The 8-byte floating-point value to write. Writes the text representation of a 8-byte floating-point value to the text stream, followed by a line terminator. - property, if not `null`, specifies the culture-specific formatting. For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - The line terminator is defined by the field. - + property, if not `null`, specifies the culture-specific formatting. For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + The line terminator is defined by the field. + ]]> The is closed. @@ -3363,15 +3365,15 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The 4-byte signed integer to write. Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator. - method. The property, if not `null`, specifies the culture-specific formatting. - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. The property, if not `null`, specifies the culture-specific formatting. + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -3432,15 +3434,15 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The 8-byte signed integer to write. Writes the text representation of an 8-byte signed integer to the text stream, followed by a line terminator. - method. The property, if not `null`, specifies the culture-specific formatting. - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. The property, if not `null`, specifies the culture-specific formatting. + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -3502,7 +3504,7 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The object to write. If is , only the line terminator is written. Writes the text representation of an object to the text stream, by calling the method on that object, followed by a line terminator. - The char span value to write to the text stream. Writes the text representation of a character span to the text stream, followed by a line terminator. - The string, as a string builder, to write to the text stream. Writes the text representation of a string builder to the text stream, followed by a line terminator. - The 4-byte unsigned integer to write. Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator. - method. The property, if not `null`, specifies the culture-specific formatting. - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. The property, if not `null`, specifies the culture-specific formatting. + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -3904,15 +3906,15 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The 8-byte unsigned integer to write. Writes the text representation of an 8-byte unsigned integer to the text stream, followed by a line terminator. - method. The property, if not `null`, specifies the culture-specific formatting. - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method. The property, if not `null`, specifies the culture-specific formatting. + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The is closed. @@ -3982,45 +3984,45 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The object to format and write. Writes a formatted string and a new line to the text stream, using the same semantics as the method. - . Because this overload has only a single object in its parameter list, the value of *index* must always be 0. If there is no parameter in the *index* position, a is thrown.| -|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| -|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| - - The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". - - This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . - - If a specified object is not referenced in the format string, it is ignored. - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . Because this overload has only a single object in its parameter list, the value of *index* must always be 0. If there is no parameter in the *index* position, a is thrown.| +|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| +|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| + + The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". + + This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . + + If a specified object is not referenced in the format string, it is ignored. + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -4028,10 +4030,10 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The is closed. An I/O error occurs. - is not a valid composite format string. - - -or- - + is not a valid composite format string. + + -or- + The index of a format item is less than 0 (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is one). @@ -4106,55 +4108,55 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo An object array that contains zero or more objects to format and write. Writes out a formatted string and a new line to the text stream, using the same semantics as . - . Because this overload has an array in its parameter list, the value of *index* must always be less than the length of the array. If there is no parameter in the *index* position, a is thrown.| -|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| -|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| - - The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". - - This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . - - If a specified object is not referenced in the format string, it is ignored. - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . Because this overload has an array in its parameter list, the value of *index* must always be less than the length of the array. If there is no parameter in the *index* position, a is thrown.| +|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| +|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| + + The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". + + This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . + + If a specified object is not referenced in the format string, it is ignored. + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> A string or object is passed in as . The is closed. An I/O error occurs. - is not a valid composite format string. - - -or- - + is not a valid composite format string. + + -or- + The index of a format item is less than 0 (zero), or greater than or equal to the length of the array. @@ -4216,17 +4218,17 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The maximum number of characters to write. Writes a subarray of characters to the text stream, followed by a line terminator. - method followed by for each character in `buffer` between `index` and (`index` + `count`). - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + method followed by for each character in `buffer` between `index` and (`index` + `count`). + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> The buffer length minus is less than . @@ -4301,45 +4303,45 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The second object to format and write. Writes a formatted string and a new line to the text stream, using the same semantics as the method. - . Because this overload has two objects in its parameter list, the value of *index* must always be 0 or 1. If there is no parameter in the *index* position, a is thrown.| -|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| -|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| - - The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". - - This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . - - If a specified object is not referenced in the format string, it is ignored. - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . Because this overload has two objects in its parameter list, the value of *index* must always be 0 or 1. If there is no parameter in the *index* position, a is thrown.| +|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| +|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| + + The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". + + This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . + + If a specified object is not referenced in the format string, it is ignored. + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -4347,10 +4349,10 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The is closed. An I/O error occurs. - is not a valid composite format string. - - -or- - + is not a valid composite format string. + + -or- + The index of a format item is less than 0 (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is two). @@ -4421,45 +4423,45 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The third object to format and write. Writes out a formatted string and a new line to the text stream, using the same semantics as . - . Because this overload has three objects in its parameter list, the value of *index* must always be 0, 1, or 2. If there is no parameter in the *index* position, a is thrown.| -|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| -|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| - - The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". - - This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . - - If a specified object is not referenced in the format string, it is ignored. - - The line terminator is defined by the field. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + . Because this overload has three objects in its parameter list, the value of *index* must always be 0, 1, or 2. If there is no parameter in the *index* position, a is thrown.| +|,*length*|The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.| +|:*formatString*|A standard or custom format string that is supported by the object to be formatted. Possible values for *formatString* are the same as the values supported by the object's `ToString(string format)` method. If *formatString* is not specified and the object to be formatted implements the interface, `null` is passed as the value of the `format` parameter that is used as the format string.| + + The leading and trailing brace characters, "{" and "}", are required. To specify a single literal brace character in `format`, specify two leading or trailing brace characters; that is, "{{" or "}}". + + This method does not search the specified string for individual newline characters (hexadecimal 0x000a) and replace them with . + + If a specified object is not referenced in the format string, it is ignored. + + The line terminator is defined by the field. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> @@ -4467,10 +4469,10 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo The is closed. An I/O error occurs. - is not a valid composite format string. - - -or- - + is not a valid composite format string. + + -or- + The index of a format item is less than 0 (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is three). @@ -4618,13 +4620,13 @@ This method stores in the task it returns all non-usage exceptions that the meth Asynchronously writes a character to the text stream, followed by a line terminator. A task that represents the asynchronous write operation. - field. - - The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + field. + + The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -4689,11 +4691,11 @@ This method stores in the task it returns all non-usage exceptions that the meth Asynchronously writes an array of characters to the text stream, followed by a line terminator. A task that represents the asynchronous write operation. - field. - + field. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -4758,13 +4760,13 @@ This method stores in the task it returns all non-usage exceptions that the meth Asynchronously writes a string to the text stream, followed by a line terminator. A task that represents the asynchronous write operation. - field. - - The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. - + field. + + The class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the method, see the method. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -4816,14 +4818,15 @@ This method stores in the task it returns all non-usage exceptions that the meth Asynchronously writes the text representation of a character memory region to the text stream, followed by a line terminator. A task that represents the asynchronous write operation. - field. - + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -4871,11 +4874,12 @@ The line terminator is defined by the fi ## Remarks The line terminator is defined by the field. - + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.IO/UnmanagedMemoryStream.xml b/xml/System.IO/UnmanagedMemoryStream.xml index 10abfa87a0d..cec1e20a43d 100644 --- a/xml/System.IO/UnmanagedMemoryStream.xml +++ b/xml/System.IO/UnmanagedMemoryStream.xml @@ -60,18 +60,18 @@ Provides access to unmanaged blocks of memory from managed code. - class. A block of unmanaged memory is allocated and de-allocated using the class. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/Overview/sample.cs" id="Snippet1"::: - + +## Examples + The following code example demonstrates how to read from and write to unmanaged memory using the class. A block of unmanaged memory is allocated and de-allocated using the class. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/Overview/sample.cs" id="Snippet1"::: + ]]> @@ -187,26 +187,26 @@ The length of the memory to use. Initializes a new instance of the class using the specified location and memory length. - class, and by default sets the property to `false` and the property to `true`. The property is set to the value of the `length` parameter and cannot be changed. - - - -## Examples - The following code example demonstrates how to read from and write to unmanaged memory using the class. A block of unmanaged memory is allocated and de-allocated using the class. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: - + class, and by default sets the property to `false` and the property to `true`. The property is set to the value of the `length` parameter and cannot be changed. + + + +## Examples + The following code example demonstrates how to read from and write to unmanaged memory using the class. A block of unmanaged memory is allocated and de-allocated using the class. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: + ]]> The user does not have the required permission. The value is . - The value is less than zero. - + The value is less than zero. + -or- - + The is large enough to cause an overflow. @@ -322,34 +322,34 @@ One of the values. Initializes a new instance of the class using the specified location, memory length, total amount of memory, and file access values. - , and properties. Note that specifying does not guarantee that the stream will be writable. The access parameters allow the implementer to create an object whose implementation can match the actual stream that is exposed. - - - -## Examples - The following code example demonstrates how to read from and write to unmanaged memory using the class. A block of unmanaged memory is allocated and de-allocated using the class. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/Overview/sample.cs" id="Snippet1"::: - + , and properties. Note that specifying does not guarantee that the stream will be writable. The access parameters allow the implementer to create an object whose implementation can match the actual stream that is exposed. + + + +## Examples + The following code example demonstrates how to read from and write to unmanaged memory using the class. A block of unmanaged memory is allocated and de-allocated using the class. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/Overview/sample.cs" id="Snippet1"::: + ]]> The user does not have the required permission. The value is . - The value is less than zero. - + The value is less than zero. + -or- - - The value is less than zero. - + + The value is less than zero. + -or- - + The value is greater than the value. @@ -459,18 +459,18 @@ if the object was created by a constructor with an parameter that did not include reading the stream and if the stream is closed; otherwise, . - class. A block of unmanaged memory is allocated and de-allocated using the class. In this example, an object is passed to a method which checks the property before attempting to display the contents to the console. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: - + class. A block of unmanaged memory is allocated and de-allocated using the class. In this example, an object is passed to a method which checks the property before attempting to display the contents to the console. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: + ]]> @@ -525,11 +525,11 @@ if the stream is closed; otherwise, . - @@ -584,18 +584,18 @@ if the object was created by a constructor with an parameter value that supports writing or was created by a constructor that had no parameters, or if the stream is closed; otherwise, . - class. A block of unmanaged memory is allocated and de-allocated using the class. In this example, an object is passed to a method which checks the property before attempting to write the data to the stream. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: - + class. A block of unmanaged memory is allocated and de-allocated using the class. In this example, an object is passed to a method which checks the property before attempting to write the data to the stream. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: + ]]> @@ -643,11 +643,11 @@ Gets the stream length (size) or the total amount of memory assigned to a stream (capacity). The size or capacity of the stream. - The stream is closed. @@ -706,19 +706,19 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. - + method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). @@ -766,11 +766,11 @@ Overrides the method so that no action is performed. - base class. Since any data is written to RAM, this method is redundant. - + base class. Since any data is written to RAM, this method is redundant. + ]]> The stream is closed. @@ -828,15 +828,16 @@ Overrides the method so that the operation is cancelled if specified, but no other action is performed. A task that represents the asynchronous flush operation. - calls the method, which means that no action performed. - + calls the method, which means that no action performed. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -911,22 +912,22 @@ constructor. It supports methods that need to initialize the pointer before setting stream variables and, therefore, cannot call the parameterized constructor. Such methods should use the parameterless constructor, , initialize the pointer, and then invoke the method. +This method is equivalent to the constructor. It supports methods that need to initialize the pointer before setting stream variables and, therefore, cannot call the parameterized constructor. Such methods should use the parameterless constructor, , initialize the pointer, and then invoke the method. ]]> The user does not have the required permission. The value is . - The value is less than zero. - + The value is less than zero. + -or- - - The value is less than zero. - + + The value is less than zero. + -or- - + The value is large enough to cause an overflow. @@ -1038,18 +1039,18 @@ This method is equivalent to the Gets the length of the data in a stream. The length of the data in the stream. - class. A block of unmanaged memory is allocated and de-allocated using the class. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: - + class. A block of unmanaged memory is allocated and de-allocated using the class. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: + ]]> The stream is closed. @@ -1108,13 +1109,13 @@ This method is equivalent to the Gets or sets the current position in a stream. The current position in the stream. - and methods. will return 0 and will throw a . This support is primarily for design and code compatibility with basic stream operations. - + and methods. will return 0 and will throw a . This support is primarily for design and code compatibility with basic stream operations. + ]]> The stream is closed. @@ -1177,11 +1178,11 @@ This method is equivalent to the Gets or sets a byte pointer to a stream based on the current position in the stream. A byte pointer. - property to zero, and then call this property. - + property to zero, and then call this property. + ]]> The current position is larger than the capacity of the stream. @@ -1297,33 +1298,33 @@ This method is equivalent to the Reads the specified number of bytes into the specified array. The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. - method returns zero only after reaching the end of the stream. Otherwise, always reads at least one byte from the stream before returning. If no data is available from the stream upon a call to , the method will block until at least one byte of data can be returned. An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. - - - -## Examples - The following code example demonstrates how to read from and write to unmanaged memory using the class. A block of unmanaged memory is allocated and de-allocated using the class. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/Overview/sample.cs" id="Snippet1"::: - + method returns zero only after reaching the end of the stream. Otherwise, always reads at least one byte from the stream before returning. If no data is available from the stream upon a call to , the method will block until at least one byte of data can be returned. An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. + + + +## Examples + The following code example demonstrates how to read from and write to unmanaged memory using the class. A block of unmanaged memory is allocated and de-allocated using the class. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/Overview/sample.cs" id="Snippet1"::: + ]]> The stream is closed. - The underlying memory does not support reading. - + The underlying memory does not support reading. + -or- - + The property is set to . The parameter is set to . - The parameter is less than zero. - + The parameter is less than zero. + -or- - + The parameter is less than zero. The length of the buffer array minus the parameter is less than the parameter. @@ -1369,6 +1370,7 @@ This method is equivalent to the Asynchronously reads the unmanaged memory stream bytes into the memory region. A task that represents the asynchronous read operation, and wraps the total number of bytes read into the buffer. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1429,15 +1431,16 @@ This method is equivalent to the Asynchronously reads the specified number of bytes into the specified array. A task that represents the asynchronous read operation. The value of the parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - of the property of the returned task. - + of the property of the returned task. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1490,25 +1493,25 @@ This method is equivalent to the Reads a byte from a stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. The unsigned byte cast to an object, or -1 if at the end of the stream. - class. A block of unmanaged memory is allocated and de-allocated using the class. In this example, an object is passed to a method which checks the property before attempting to read and display the contents to the console. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: - + class. A block of unmanaged memory is allocated and de-allocated using the class. In this example, an object is passed to a method which checks the property before attempting to read and display the contents to the console. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: + ]]> The stream is closed. - The underlying memory does not support reading. - + The underlying memory does not support reading. + -or- - + The current position is at the end of the stream. @@ -1561,11 +1564,11 @@ This method is equivalent to the Sets the current position of the current stream to the given value. The new position in the stream. - . - + . + ]]> An attempt was made to seek before the beginning of the stream. @@ -1627,26 +1630,26 @@ This method is equivalent to the The length of the stream. Sets the length of a stream to a specified value. - to work. - + to work. + ]]> An I/O error has occurred. The stream is closed. - The underlying memory does not support writing. - + The underlying memory does not support writing. + -or- - + An attempt is made to write to the stream and the property is . - The specified exceeds the capacity of the stream. - + The specified exceeds the capacity of the stream. + -or- - + The specified is negative. @@ -1754,33 +1757,33 @@ This method is equivalent to the The number of bytes to write to the current stream. Writes a block of bytes to the current stream using data from a buffer. - class. A block of unmanaged memory is allocated and de-allocated using the class. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/Overview/sample.cs" id="Snippet1"::: - + class. A block of unmanaged memory is allocated and de-allocated using the class. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/Overview/sample.cs" id="Snippet1"::: + ]]> The stream is closed. - The underlying memory does not support writing. - + The underlying memory does not support writing. + -or- - - An attempt is made to write to the stream and the property is . - + + An attempt is made to write to the stream and the property is . + -or- - - The value is greater than the capacity of the stream. - + + The value is greater than the capacity of the stream. + -or- - + The position is at the end of the stream capacity. An I/O error occurs. One of the specified parameters is less than zero. @@ -1837,6 +1840,7 @@ If an exception occurs during the write operation, it will be set as the + The cancellation token was canceled. This exception is stored into the returned task. @@ -1897,15 +1901,16 @@ If an exception occurs during the write operation, it will be set as the Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. - of the property of the returned task. - + of the property of the returned task. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1960,24 +1965,24 @@ If an exception occurs during the write operation, it will be set as the A byte value written to the stream. Writes a byte to the current position in the file stream. - class. A block of unmanaged memory is allocated and de-allocated using the class. In this example, an object is passed to a method which checks the property before attempting to write the data to the stream. - - :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: - + class. A block of unmanaged memory is allocated and de-allocated using the class. In this example, an object is passed to a method which checks the property before attempting to write the data to the stream. + + :::code language="csharp" source="~/snippets/csharp/System.IO/UnmanagedMemoryStream/.ctor/program.cs" id="Snippet00"::: + ]]> The stream is closed. - The underlying memory does not support writing. - + The underlying memory does not support writing. + -or- - - An attempt is made to write to the stream and the property is . - + + An attempt is made to write to the stream and the property is . + -or- - + The current position is at the end of the capacity of the stream. The supplied causes the stream exceed its maximum capacity. diff --git a/xml/System.Linq/ParallelEnumerable.xml b/xml/System.Linq/ParallelEnumerable.xml index 9e00620a32a..843944b7f10 100644 --- a/xml/System.Linq/ParallelEnumerable.xml +++ b/xml/System.Linq/ParallelEnumerable.xml @@ -11108,6 +11108,7 @@ Parallel LINQ (PLINQ) How to: Cancel a PLINQ Query Cancellation + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http.Json/HttpClientJsonExtensions.xml b/xml/System.Net.Http.Json/HttpClientJsonExtensions.xml index 4de9483078e..fb71a1fe7cf 100644 --- a/xml/System.Net.Http.Json/HttpClientJsonExtensions.xml +++ b/xml/System.Net.Http.Json/HttpClientJsonExtensions.xml @@ -66,6 +66,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -107,6 +108,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -157,6 +159,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -197,6 +200,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -240,6 +244,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -273,6 +278,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -323,6 +329,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -366,6 +373,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -418,6 +426,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -460,6 +469,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -505,6 +515,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -540,6 +551,7 @@ The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -597,6 +609,7 @@ This method uses + The cancellation token was canceled. This exception is stored into the returned task. @@ -647,6 +660,7 @@ This method uses + The cancellation token was canceled. This exception is stored into the returned task. @@ -698,6 +712,7 @@ This method uses Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -738,6 +753,7 @@ This method uses Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -782,6 +798,7 @@ This method uses Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -815,6 +832,7 @@ This method uses Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -874,6 +892,7 @@ This method uses + The cancellation token was canceled. This exception is stored into the returned task. @@ -926,6 +945,7 @@ This method uses + The cancellation token was canceled. This exception is stored into the returned task. @@ -979,6 +999,7 @@ This method uses Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1021,6 +1042,7 @@ This method uses Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1067,6 +1089,7 @@ This method uses Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1102,6 +1125,7 @@ This method uses Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1155,6 +1179,7 @@ This method uses The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1201,6 +1226,7 @@ This method uses The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1255,6 +1281,7 @@ This method uses The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1299,6 +1326,7 @@ This method uses The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1346,6 +1374,7 @@ This method uses The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1383,6 +1412,7 @@ This method uses The task object representing the asynchronous operation. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1445,6 +1475,7 @@ This method uses + The cancellation token was canceled. This exception is stored into the returned task. @@ -1500,6 +1531,7 @@ This method uses + The cancellation token was canceled. This exception is stored into the returned task. @@ -1555,6 +1587,7 @@ This method uses Sends a POST request to the specified Uri containing the serialized as JSON in the request body. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1599,6 +1632,7 @@ This method uses Sends a POST request to the specified Uri containing the serialized as JSON in the request body. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1647,6 +1681,7 @@ This method uses Sends a POST request to the specified Uri containing the serialized as JSON in the request body. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1684,6 +1719,7 @@ This method uses Sends a POST request to the specified Uri containing the serialized as JSON in the request body. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1746,6 +1782,7 @@ This method uses + The cancellation token was canceled. This exception is stored into the returned task. @@ -1801,6 +1838,7 @@ This method uses + The cancellation token was canceled. This exception is stored into the returned task. @@ -1856,6 +1894,7 @@ This method uses Send a PUT request to the specified Uri containing the serialized as JSON in the request body. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1900,6 +1939,7 @@ This method uses Send a PUT request to the specified Uri containing the serialized as JSON in the request body. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1948,6 +1988,7 @@ This method uses Send a PUT request to the specified Uri containing the serialized as JSON in the request body. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1985,6 +2026,7 @@ This method uses Send a PUT request to the specified Uri containing the serialized as JSON in the request body. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http.Json/HttpContentJsonExtensions.xml b/xml/System.Net.Http.Json/HttpContentJsonExtensions.xml index 0454e6a8dc9..c540f7b5442 100644 --- a/xml/System.Net.Http.Json/HttpContentJsonExtensions.xml +++ b/xml/System.Net.Http.Json/HttpContentJsonExtensions.xml @@ -60,6 +60,7 @@ Reads the HTTP content and returns the value that results from deserializing the content as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -91,6 +92,7 @@ Reads the HTTP content and returns the value that results from deserializing the content as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -135,6 +137,7 @@ Reads the HTTP content and returns the value that results from deserializing the content as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -168,6 +171,7 @@ Reads the HTTP content and returns the value that results from deserializing the content as JSON in an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http.Json/JsonContent.xml b/xml/System.Net.Http.Json/JsonContent.xml index d20dedf3c8e..6b7625a66b6 100644 --- a/xml/System.Net.Http.Json/JsonContent.xml +++ b/xml/System.Net.Http.Json/JsonContent.xml @@ -157,6 +157,7 @@ To be added. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -217,6 +218,7 @@ To be added. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/ByteArrayContent.xml b/xml/System.Net.Http/ByteArrayContent.xml index 9540cbcb80c..a43917c751b 100644 --- a/xml/System.Net.Http/ByteArrayContent.xml +++ b/xml/System.Net.Http/ByteArrayContent.xml @@ -80,11 +80,11 @@ The content used to initialize the . Initializes a new instance of the class. - class does not internally copy the provided byte array but keeps a reference to it instead. Callers should not modify the data in the array until after the content is sent. - + class does not internally copy the provided byte array but keeps a reference to it instead. Callers should not modify the data in the array until after the content is sent. + ]]> The parameter is . @@ -126,28 +126,28 @@ The class does not internally copy the p The number of bytes in the starting from the parameter used to initialize the . Initializes a new instance of the class. - class does not internally copy the provided byte array but keeps a reference to it instead. Callers should not modify the data in the array until after the content is sent. - + class does not internally copy the provided byte array but keeps a reference to it instead. Callers should not modify the data in the array until after the content is sent. + Only the range specified by the `offset` parameter and the `count` parameter is used as content. - + ]]> The parameter is . - The parameter is less than zero. - - -or- - - The parameter is greater than the length of content specified by the parameter. - - -or- - - The parameter is less than zero. - - -or- - + The parameter is less than zero. + + -or- + + The parameter is greater than the length of content specified by the parameter. + + -or- + + The parameter is less than zero. + + -or- + The parameter is greater than the length of content specified by the parameter - minus the parameter. @@ -179,6 +179,7 @@ The class does not internally copy the p Creates an HTTP content stream for reading. It uses the memory from the as a backing store. The HTTP content stream. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -214,11 +215,11 @@ The class does not internally copy the p Creates an HTTP content stream as an asynchronous operation for reading whose backing store is memory from the . The task object representing the asynchronous operation. - object will complete after all of the content stream has been created. - + object will complete after all of the content stream has been created. + ]]> @@ -254,6 +255,7 @@ The class does not internally copy the p The cancellation token to cancel the operation. Serializes and writes the byte array provided in the constructor to an HTTP content stream. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -299,11 +301,11 @@ The class does not internally copy the p Serialize and write the byte array provided in the constructor to an HTTP content stream as an asynchronous operation. The task object representing the asynchronous operation. - object completes, the whole byte array has been written to the `stream` parameter. - + object completes, the whole byte array has been written to the `stream` parameter. + ]]> @@ -340,13 +342,14 @@ The class does not internally copy the p Serialize and write the byte array provided in the constructor to an HTTP content stream as an asynchronous operation. The task object representing the asynchronous operation. - object completes, the whole byte array has been written to the `stream` parameter. - + object completes, the whole byte array has been written to the `stream` parameter. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -386,13 +389,13 @@ The class does not internally copy the p if is a valid length; otherwise, . - method gives a derived content type the ability to calculate the content length. This is useful for content types which are able to easily calculate the content length. If computing the content length is not possible or expensive (would require the system to buffer the whole content where the serialization would be expensive or require the system to allocate a lot of memory), this method can return `false`. If this method returns `false`, this implies that either chunked transfer is needed or the content must get buffered before being sent to the server. - - This method always returned `true` for . - + method gives a derived content type the ability to calculate the content length. This is useful for content types which are able to easily calculate the content length. If computing the content length is not possible or expensive (would require the system to buffer the whole content where the serialization would be expensive or require the system to allocate a lot of memory), this method can return `false`. If this method returns `false`, this implies that either chunked transfer is needed or the content must get buffered before being sent to the server. + + This method always returned `true` for . + ]]> diff --git a/xml/System.Net.Http/CFNetworkHandler.xml b/xml/System.Net.Http/CFNetworkHandler.xml index a703e3e89b8..40ff44a34b5 100644 --- a/xml/System.Net.Http/CFNetworkHandler.xml +++ b/xml/System.Net.Http/CFNetworkHandler.xml @@ -132,6 +132,7 @@ To be added. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/DelegatingHandler.xml b/xml/System.Net.Http/DelegatingHandler.xml index c18611b77a0..b2f17d18147 100644 --- a/xml/System.Net.Http/DelegatingHandler.xml +++ b/xml/System.Net.Http/DelegatingHandler.xml @@ -34,13 +34,13 @@ A type for HTTP handlers that delegate the processing of HTTP response messages to another handler, called the inner handler. - property before calling ; otherwise, an will be thrown. - - Note that property may be a delegating handler as well. This approach allows the creation of handler stacks to process the HTTP response messages. - + + Note that property may be a delegating handler as well. This approach allows the creation of handler stacks to process the HTTP response messages. + ]]> @@ -85,11 +85,11 @@ Creates a new instance of the class. - . - + . + ]]> @@ -199,13 +199,13 @@ Gets or sets the inner handler which processes the HTTP response messages. The inner handler for HTTP response messages. - property can only be set before the class is used (the method is called). - - Note that property may be a delegating handler too, although this is uncommon. This approach allows the creation of handler stacks for the HTTP response messages. - + property can only be set before the class is used (the method is called). + + Note that property may be a delegating handler too, although this is uncommon. This approach allows the creation of handler stacks for the HTTP response messages. + ]]> @@ -240,14 +240,15 @@ Sends an HTTP request to the inner handler to send to the server. An HTTP response message. - method is mainly used by the system and not by applications. When this method is called, it calls the method on the inner handler. - + + The method is mainly used by the system and not by applications. When this method is called, it calls the method on the inner handler. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -288,16 +289,17 @@ Sends an HTTP request to the inner handler to send to the server as an asynchronous operation. The task object representing the asynchronous operation. - method forwards the HTTP request to the inner handler to send to the server as an asynchronous operation. - - The method is mainly used by the system and not by applications. When this method is called, it calls the method on the inner handler. - + method forwards the HTTP request to the inner handler to send to the server as an asynchronous operation. + + The method is mainly used by the system and not by applications. When this method is called, it calls the method on the inner handler. + ]]> The was . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/FormUrlEncodedContent.xml b/xml/System.Net.Http/FormUrlEncodedContent.xml index a2312a6f4c4..2074be51cee 100644 --- a/xml/System.Net.Http/FormUrlEncodedContent.xml +++ b/xml/System.Net.Http/FormUrlEncodedContent.xml @@ -103,13 +103,14 @@ Serialize and write all name/value tuples provided in the constructor to an HTTP content stream as an asynchronous operation. The task object representing the asynchronous operation. - object completes, the all name/value tuples has been written to the `stream` parameter. - + object completes, the all name/value tuples has been written to the `stream` parameter. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/HttpClient.xml b/xml/System.Net.Http/HttpClient.xml index ad1220da893..98f9ced8a90 100644 --- a/xml/System.Net.Http/HttpClient.xml +++ b/xml/System.Net.Http/HttpClient.xml @@ -34,11 +34,11 @@ Provides a class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. - class instance acts as a session to send HTTP requests. An instance is a collection of settings applied to all requests executed by that instance. In addition, every instance uses its own connection pool, isolating its requests from requests executed by other instances. +The class instance acts as a session to send HTTP requests. An instance is a collection of settings applied to all requests executed by that instance. In addition, every instance uses its own connection pool, isolating its requests from requests executed by other instances. ### Instancing @@ -47,7 +47,7 @@ The class instance acts as a session to send H You can configure additional options by passing in a "handler", such as (or in .NET Core 2.1 or later), as part of the constructor. The connection properties on the handler cannot be changed once a request has been submitted, so one reason to create a new HttpClient instance would be if you need to change the connection properties. If different requests require different settings, this may also lead to an application having multiple instances, where each instance is configured appropriately, and then requests are issued on the relevant client. HttpClient only resolves DNS entries when a connection is created. It does not track any time to live (TTL) durations specified by the DNS server. If DNS entries change regularly, which can happen in some container scenarios, the client won't respect those updates. To solve this issue, you can limit the lifetime of the connection by setting the property, so that DNS lookup is required when the connection is replaced. - + ```csharp public class GoodController : ApiController { @@ -70,7 +70,7 @@ As an alternative to creating only one HttpClient instance, you can also use also acts as a base class for more specific HTTP clients. An example would be a FacebookHttpClient that provides additional methods specific to a Facebook web service (for example, a `GetFriends` method). Derived classes should not override the virtual methods on the class. Instead, use a constructor overload that accepts to configure any pre-request or post-request processing. - + ### Transports The is a high-level API that wraps the lower-level functionality available on each platform where it runs. @@ -96,8 +96,8 @@ Users can also configure a specific transport for is used to send requests to the server. This behavior can be modified by specifying a different handler in one of the constructor overloads with an parameter. If you require features like authentication or caching, you can use to configure settings and the instance can be passed to the constructor. The returned handler can be passed to a constructor overload that has an parameter. - + By default on .NET Framework and Mono, is used to send requests to the server. This behavior can be modified by specifying a different handler in one of the constructor overloads with an parameter. If you require features like authentication or caching, you can use to configure settings and the instance can be passed to the constructor. The returned handler can be passed to a constructor overload that has an parameter. + #### .NET Core Starting with .NET Core 2.1, the class instead of provides the implementation used by higher-level HTTP networking classes such as . The use of offers a number of advantages: @@ -134,13 +134,13 @@ By default, HttpClient methods (except parameter available on some method overloads. This argument can be used to specify if the should be considered complete after reading just the response headers, or after reading and buffering the response content. - -If your app that uses and related classes in the namespace intends to download large amounts of data (50 megabytes or more), then the app should stream those downloads and not use the default buffering. If you use the default buffering, the client memory usage will get very large, potentially resulting in substantially reduced performance. - + +If your app that uses and related classes in the namespace intends to download large amounts of data (50 megabytes or more), then the app should stream those downloads and not use the default buffering. If you use the default buffering, the client memory usage will get very large, potentially resulting in substantially reduced performance. + ### Thread safety - The following methods are thread safe: - + The following methods are thread safe: + - - - @@ -175,16 +175,16 @@ You can set some additional timeouts if you pass in a | If a connection in the connection pool is idle for this long, the connection is closed. | | | If request has an "Expect: 100-continue" header, it delays sending content until the timeout or until a "100-continue" response is received. | -HttpClient only resolves DNS entries when the connections are created. It does not track any time to live (TTL) durations specified by the DNS server. If DNS entries are changing regularly, which can happen in some container scenarios, you can use the to limit the lifetime of the connection so that DNS lookup is required when replacing the connection. +HttpClient only resolves DNS entries when the connections are created. It does not track any time to live (TTL) durations specified by the DNS server. If DNS entries are changing regularly, which can happen in some container scenarios, you can use the to limit the lifetime of the connection so that DNS lookup is required when replacing the connection. ## Examples - :::code language="csharp" source="~/snippets/csharp/System.Net.Http/HttpClient/source.cs" id="Snippet1"::: - :::code language="fsharp" source="~/snippets/fsharp/System.Net.Http/HttpClient/source.fs" id="Snippet1"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Http/HttpClient/source.cs" id="Snippet1"::: + :::code language="fsharp" source="~/snippets/fsharp/System.Net.Http/HttpClient/source.fs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/system.net.http.httpclient/vb/source.vb" id="Snippet1"::: The preceding code example uses an `async Task Main()` entry point. That feature requires C# 7.1 or later. - + ]]> Guidelines for using HttpClient @@ -201,30 +201,30 @@ HttpClient only resolves DNS entries when the connections are created. It does n Initializes a new instance of the class. - is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. Below is an example using HttpClient correctly. - -```csharp -public class GoodController : ApiController -{ - private static readonly HttpClient HttpClient; - - static GoodController() - { - HttpClient = new HttpClient(); - } -} + is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. Below is an example using HttpClient correctly. + +```csharp +public class GoodController : ApiController +{ + private static readonly HttpClient HttpClient; + + static GoodController() + { + HttpClient = new HttpClient(); + } +} ``` ```vb Public Class GoodController - Inherits ApiController - + Inherits ApiController + Private Shared ReadOnly HttpClient As HttpClient - - Shared Sub New() + + Shared Sub New() HttpClient = New HttpClient() End Sub End Class @@ -262,8 +262,8 @@ End Class Initializes a new instance of the class using a that is disposed when this instance is disposed. - @@ -301,11 +301,11 @@ Using this constructor is equivalent to calling the [`HttpClient(new HttpClientH The HTTP handler stack to use for sending requests. Initializes a new instance of the class with the specified handler. The handler is disposed when this instance is disposed. - The is . @@ -382,13 +382,13 @@ The specified `handler` will be disposed of by calling [HttpClient.Dispose](xref Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests. The base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests. - with a relative Uri, the message Uri will be added to the property to create an absolute Uri. - + with a relative Uri, the message Uri will be added to the property to create an absolute Uri. + Note that all characters after the right-most "/" in the base URI are excluded when combined with the message URI. See [RFC 3986](https://tools.ietf.org/html/rfc3986) Uniform Resource Identifier (URI) Generic Syntax specification. - + ]]> @@ -425,11 +425,11 @@ The specified `handler` will be disposed of by calling [HttpClient.Dispose](xref Cancel all pending requests on this instance. - instance can still be used to execute additional requests. - + instance can still be used to execute additional requests. + ]]> @@ -460,10 +460,10 @@ The specified `handler` will be disposed of by calling [HttpClient.Dispose](xref Gets or sets the global Http proxy. A proxy used by every call that instantiates a . -  instances use if no proxy is set explicitly in the  passed through its constructor. +This static property determines the default proxy that all  instances use if no proxy is set explicitly in the  passed through its constructor. The default instance returned by this property will initialize following a different set of rules depending on your platform: * **For Windows:** Reads proxy configuration from environment variables or, if those are not defined, from the user's proxy settings. @@ -518,11 +518,11 @@ The proxy server may be a hostname or IP address, optionally followed by a colon Gets the headers which should be sent with each request. The headers which should be sent with each request. - @@ -553,9 +553,9 @@ The proxy server may be a hostname or IP address, optionally followed by a colon Gets or sets the default HTTP version used on subsequent requests made by this instance. The default version to use for any requests made with this instance. - by default. The `DefaultRequestVersion` property specifies the default HTTP version to use for requests sent using this instance when it constructs the to send, specifically with calls to methods such as , , , , , , , and . @@ -594,9 +594,9 @@ The `DefaultRequestVersion` property can be changed as long as the Gets or sets the default version policy for implicitly created requests in convenience methods, for example, and . The HttpVersionPolicy used when the HTTP connection is established. - or overloads that accept an . ]]> @@ -658,10 +658,10 @@ This property has no effect on any of the Send a DELETE request to the specified Uri as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -720,10 +720,10 @@ The is not an absolute URI. Send a DELETE request to the specified Uri as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -791,10 +791,10 @@ The is not an absolute URI. Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -814,6 +814,7 @@ The is not an absolute URI. is not set. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -855,10 +856,10 @@ The is not an absolute URI. Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -878,6 +879,7 @@ The is not an absolute URI. is not set. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -916,15 +918,15 @@ The is not an absolute URI. to release both managed and unmanaged resources; to releases only unmanaged resources. Releases the unmanaged resources used by the and optionally disposes of the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - - When this method is called, the method is called to abort all pending requests. - + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + + When this method is called, the method is called to abort all pending requests. + ]]> @@ -939,11 +941,11 @@ The is not an absolute URI. Send a GET request to the specified Uri as an asynchronous operation. - @@ -992,9 +994,9 @@ The is not an absolute URI. Send a GET request to the specified Uri as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. The behavior is the same as if has been explicitly specified. > [!NOTE] @@ -1047,9 +1049,9 @@ The is not an absolute URI. Send a GET request to the specified Uri as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. The behavior is the same as if has been explicitly specified. > [!NOTE] @@ -1110,10 +1112,10 @@ The is not an absolute URI. Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation. The task object representing the asynchronous operation. - object will complete based on the `completionOption` parameter after the part or all of the response (including content) is read. + object will complete based on the `completionOption` parameter after the part or all of the response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -1174,9 +1176,9 @@ The is not an absolute URI. Send a GET request to the specified Uri with a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. The behavior is the same as if has been explicitly specified. > [!NOTE] @@ -1190,6 +1192,7 @@ The is not an absolute URI. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. The provided request URI is not valid relative or absolute URI. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1231,10 +1234,10 @@ The is not an absolute URI. Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation. The task object representing the asynchronous operation. - object will complete based on the `completionOption` parameter after the part or all of the response (including content) is read. + object will complete based on the `completionOption` parameter after the part or all of the response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -1287,9 +1290,9 @@ The is not an absolute URI. Send a GET request to the specified Uri with a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. The behavior is the same as if has been explicitly specified. > [!NOTE] @@ -1302,6 +1305,7 @@ The is not an absolute URI. The must be an absolute URI or must be set. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1352,10 +1356,10 @@ The is not an absolute URI. Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete based on the `completionOption` parameter after the part or all of the response (including content) is read. + object will complete based on the `completionOption` parameter after the part or all of the response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -1368,6 +1372,7 @@ The is not an absolute URI. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. The provided request URI is not valid relative or absolute URI. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1411,10 +1416,10 @@ The is not an absolute URI. Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete based on the `completionOption` parameter after the part or all of the response (including content) is read. + object will complete based on the `completionOption` parameter after the part or all of the response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -1426,6 +1431,7 @@ The is not an absolute URI. The must be an absolute URI or must be set. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1438,11 +1444,11 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation. - @@ -1497,10 +1503,10 @@ The is not an absolute URI. Sends a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response body is read. + object will complete after the whole response body is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -1558,10 +1564,10 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response body is read. + object will complete after the whole response body is read. > [!NOTE] > In case of a timeout: @@ -1613,10 +1619,10 @@ The is not an absolute URI. Sends a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response body is read. + object will complete after the whole response body is read. > [!NOTE] > In case of a timeout: @@ -1629,6 +1635,7 @@ The is not an absolute URI. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation (or timeout for .NET Framework only). .NET Core and .NET 5 and later only: The request failed due to timeout. The provided request URI is not valid relative or absolute URI. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1661,10 +1668,10 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response body is read. + object will complete after the whole response body is read. > [!NOTE] > In case of a timeout: @@ -1676,6 +1683,7 @@ The is not an absolute URI. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation (or timeout for .NET Framework only). .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1688,11 +1696,11 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation. - @@ -1747,10 +1755,10 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation. The task object representing the asynchronous operation. - ](xref:System.Threading.Tasks.Task%601) object will complete after the response headers are read. This method does not read nor buffer the response body. + ](xref:System.Threading.Tasks.Task%601) object will complete after the response headers are read. This method does not read nor buffer the response body. > [!NOTE] > In case of a timeout: @@ -1808,10 +1816,10 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation. The task object representing the asynchronous operation. - ](xref:System.Threading.Tasks.Task%601) object will complete after the response headers are read. This method does not read nor buffer the response body. + ](xref:System.Threading.Tasks.Task%601) object will complete after the response headers are read. This method does not read nor buffer the response body. > [!NOTE] > In case of a timeout: @@ -1863,9 +1871,9 @@ The is not an absolute URI. The task object representing the asynchronous operation. ](xref:System.Threading.Tasks.Task%601) object will complete after the response headers are read. This method does not read nor buffer the response body. + +## Remarks + This operation will not block. The returned [Task\](xref:System.Threading.Tasks.Task%601) object will complete after the response headers are read. This method does not read nor buffer the response body. > [!NOTE] > In case of a timeout: @@ -1874,6 +1882,7 @@ The is not an absolute URI. > - .NET 5 and later versions throw a that nests a . ]]> + The cancellation token was canceled. This exception is stored into the returned task. The is . The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation (or timeout for .NET Framework only). @@ -1910,10 +1919,10 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation. The task object representing the asynchronous operation. - ](xref:System.Threading.Tasks.Task%601) object will complete after the response headers are read. This method does not read nor buffer the response body. + ](xref:System.Threading.Tasks.Task%601) object will complete after the response headers are read. This method does not read nor buffer the response body. > [!NOTE] > In case of a timeout: @@ -1925,6 +1934,7 @@ The is not an absolute URI. The is . The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation (or timeout for .NET Framework only). .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1937,11 +1947,11 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation. - @@ -1996,10 +2006,10 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response body is read. + object will complete after the whole response body is read. > [!NOTE] > In case of a timeout: @@ -2057,10 +2067,10 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response body is read. + object will complete after the whole response body is read. > [!NOTE] > In case of a timeout: @@ -2111,10 +2121,10 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response body is read. + object will complete after the whole response body is read. > [!NOTE] > In case of a timeout: @@ -2127,6 +2137,7 @@ The is not an absolute URI. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation (or timeout for .NET Framework only). .NET Core and .NET 5 and later only: The request failed due to timeout. The provided request URI is not valid relative or absolute URI. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2159,10 +2170,10 @@ The is not an absolute URI. Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response body is read. + object will complete after the whole response body is read. > [!NOTE] > In case of a timeout: @@ -2174,6 +2185,7 @@ The is not an absolute URI. The is . The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation (or timeout for .NET Framework only). .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2208,11 +2220,11 @@ The is not an absolute URI. Gets or sets the maximum number of bytes to buffer when reading the response content. The maximum number of bytes to buffer when reading the response content. The default value for this property is 2 gigabytes. - property to a lower value to limit the size of the response to buffer when reading the response. If the size of the response content is greater than the property, an exception is thrown. - + property to a lower value to limit the size of the response to buffer when reading the response. If the size of the response content is greater than the property, an exception is thrown. + ]]> The size specified is less than or equal to zero. @@ -2262,11 +2274,11 @@ The is not an absolute URI. Sends a PATCH request to a Uri designated as a string as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. - + object will complete after the whole response (including content) is read. + ]]> The provided request URI is not valid relative or absolute URI. @@ -2307,11 +2319,11 @@ The is not an absolute URI. Sends a PATCH request as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. - + object will complete after the whole response (including content) is read. + ]]> @@ -2360,14 +2372,15 @@ The is not an absolute URI. Sends a PATCH request with a cancellation token to a Uri represented as a string as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. - + object will complete after the whole response (including content) is read. + ]]> The provided request URI is not valid relative or absolute URI. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2407,13 +2420,14 @@ The is not an absolute URI. Sends a PATCH request with a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. - + object will complete after the whole response (including content) is read. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -2426,11 +2440,11 @@ The is not an absolute URI. Send a POST request to the specified Uri as an asynchronous operation. - @@ -2482,10 +2496,10 @@ The is not an absolute URI. Send a POST request to the specified Uri as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -2540,10 +2554,10 @@ The is not an absolute URI. Send a POST request to the specified Uri as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -2606,10 +2620,10 @@ The is not an absolute URI. Send a POST request with a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -2622,6 +2636,7 @@ The is not an absolute URI. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. The provided request URI is not valid relative or absolute URI. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2666,10 +2681,10 @@ The is not an absolute URI. Send a POST request with a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -2681,6 +2696,7 @@ The is not an absolute URI. The must be an absolute URI or must be set. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2693,11 +2709,11 @@ The is not an absolute URI. Send a PUT request to the specified Uri as an asynchronous operation. - @@ -2749,10 +2765,10 @@ The is not an absolute URI. Send a PUT request to the specified Uri as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -2807,10 +2823,10 @@ The is not an absolute URI. Send a PUT request to the specified Uri as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -2873,10 +2889,10 @@ The is not an absolute URI. Send a PUT request with a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -2889,6 +2905,7 @@ The is not an absolute URI. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. The provided request URI is not valid relative or absolute URI. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2933,10 +2950,10 @@ The is not an absolute URI. Send a PUT request with a cancellation token as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the whole response (including content) is read. + object will complete after the whole response (including content) is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -2948,6 +2965,7 @@ The is not an absolute URI. The must be an absolute URI or must be set. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3106,6 +3124,7 @@ The custom does not override If the exception nests the : The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3164,6 +3183,7 @@ The custom does not override If the exception nests the : The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3176,11 +3196,11 @@ The custom does not override Send an HTTP request as an asynchronous operation. - @@ -3221,9 +3241,9 @@ The custom does not override Send an HTTP request as an asynchronous operation. The task object representing the asynchronous operation. - object will complete once the entire response including content is read. The behavior is the same as if has been explicitly specified. > [!NOTE] @@ -3280,10 +3300,10 @@ This method stores in the task it returns all non-usage exceptions that the meth Send an HTTP request as an asynchronous operation. The task object representing the asynchronous operation. - object will complete as soon as a response is available or the entire response including content is read. + object will complete as soon as a response is available or the entire response including content is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -3339,9 +3359,9 @@ This method stores in the task it returns all non-usage exceptions that the meth Send an HTTP request as an asynchronous operation. The task object representing the asynchronous operation. - object will complete once the entire response including content is read. The behavior is the same as if has been explicitly specified. > [!NOTE] @@ -3358,6 +3378,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The request message was already sent by the instance. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3400,10 +3421,10 @@ This method stores in the task it returns all non-usage exceptions that the meth Send an HTTP request as an asynchronous operation. The task object representing the asynchronous operation. - object will complete as soon as a response is available or the entire response including content is read. + object will complete as soon as a response is available or the entire response including content is read. > [!NOTE] > In case of timeout, different exceptions are thrown on different .NET implementations. @@ -3419,6 +3440,7 @@ This method stores in the task it returns all non-usage exceptions that the meth The request message was already sent by the instance. The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. .NET Core and .NET 5 and later only: The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3453,21 +3475,21 @@ This method stores in the task it returns all non-usage exceptions that the meth Gets or sets the timespan to wait before the request times out. The timespan to wait before the request times out. - . - - A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set to a value less than 15 seconds, it may take 15 seconds or more before a is thrown to indicate a timeout on your request. - - The same timeout will apply for all requests using this instance. You may also set different timeouts for individual requests using a on a task. Note that only the shorter of the two timeouts will apply. - + . + + A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set to a value less than 15 seconds, it may take 15 seconds or more before a is thrown to indicate a timeout on your request. + + The same timeout will apply for all requests using this instance. You may also set different timeouts for individual requests using a on a task. Note that only the shorter of the two timeouts will apply. + ## Examples - + The following example sets the `Timeout` property. - + ```csharp HttpClient httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromMinutes(10); diff --git a/xml/System.Net.Http/HttpClientHandler.xml b/xml/System.Net.Http/HttpClientHandler.xml index ec31b037633..44f2108708b 100644 --- a/xml/System.Net.Http/HttpClientHandler.xml +++ b/xml/System.Net.Http/HttpClientHandler.xml @@ -345,9 +345,9 @@ After NuGet package v4.3.2, the default value of Gets the collection of security certificates that are associated with requests to the server. The X509CertificateCollection that is presented to the server when performing certificate based client authentication. - Gets or sets the maximum number of concurrent connections (per server endpoint) allowed when making requests using an object. Note that the limit is per server endpoint, so for example a value of 256 would permit 256 concurrent connections to http://www.adatum.com/ and another 256 to http://www.adventure-works.com/. The maximum number of concurrent connections (per server endpoint) allowed by an object. - @@ -991,6 +991,7 @@ handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousA If the exception nests the : The request failed due to timeout. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1045,6 +1046,7 @@ handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousA ]]> The was . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1090,7 +1092,7 @@ handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousA Gets or sets a callback method to validate the server certificate. A callback method to validate the server certificate. - can be used to obtain and validate the server certificate. @@ -1338,7 +1340,7 @@ handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousA ## Remarks Set this property to `true` when requests made by the object should, if requested by the server, be authenticated using the credentials of the currently logged on user. For client applications, this is the desired behavior in most scenarios. For middle-tier applications, such as ASP.NET applications, instead of using this property, you would typically set the property to the credentials of the client on whose behalf the request is made. - + This property doesn't affect proxy credentials. When the default (system) proxy is being used, set credentials explicitly by using the property. When the proxy is set by the property, set credentials for the proxy via its property. ]]> diff --git a/xml/System.Net.Http/HttpContent.xml b/xml/System.Net.Http/HttpContent.xml index bda1b4c67db..4df77fefd7c 100644 --- a/xml/System.Net.Http/HttpContent.xml +++ b/xml/System.Net.Http/HttpContent.xml @@ -136,6 +136,7 @@ If the content has been previously buffered, for example, by calling The was . + The cancellation token was canceled. This exception is stored into the returned task. @@ -291,6 +292,7 @@ If the content has been previously buffered, for example, by calling + The cancellation token was canceled. This exception is stored into the returned task. @@ -332,6 +334,7 @@ If the content has been previously buffered, for example, by calling + The cancellation token was canceled. This exception is stored into the returned task. @@ -373,6 +376,7 @@ Once the operation completes, the returned memory stream represents the HTTP con ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -466,6 +470,7 @@ Once the operation completes, the returned memory stream represents the HTTP con ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -807,6 +812,7 @@ When the `disposing` parameter is `true`, this method releases all resources hel ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -884,6 +890,7 @@ When the `disposing` parameter is `true`, this method releases all resources hel Serializes the HTTP content and returns a stream that represents the content. The stream that represents the HTTP content. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -997,6 +1004,7 @@ When the `disposing` parameter is `true`, this method releases all resources hel ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1090,6 +1098,7 @@ When the `disposing` parameter is `true`, this method releases all resources hel ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1124,6 +1133,7 @@ When the `disposing` parameter is `true`, this method releases all resources hel When overridden in a derived class, serializes the HTTP content to a stream. Otherwise, throws a . To be added. The method is not overridden in the derived class. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1217,6 +1227,7 @@ When the `disposing` parameter is `true`, this method releases all resources hel ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/HttpMessageHandler.xml b/xml/System.Net.Http/HttpMessageHandler.xml index 229b25208f1..b215b6f59c5 100644 --- a/xml/System.Net.Http/HttpMessageHandler.xml +++ b/xml/System.Net.Http/HttpMessageHandler.xml @@ -38,23 +38,23 @@ A base type for HTTP message handlers. - - A class used to plug a handler into a handler chain. - -2. - A simple class to derive from that supports the most common requirements for most applications. - -3. - A class that operates at the bottom of the handler chain that actually handles the HTTP transport operations. - -4. - A specialty class that operates at the bottom of the handler chain class that handles HTTP transport operations with options that are specific to the object. - - If developers derive classes from and override the method, they must make sure that can get called concurrently by different threads. - - This is necessary since methods on can be called concurrently and need a guarantee of thread safety. So if a handler is assigned to an instance, the method of the handler may get called concurrently by the instance and needs to be thread safe. - + - A class used to plug a handler into a handler chain. + +2. - A simple class to derive from that supports the most common requirements for most applications. + +3. - A class that operates at the bottom of the handler chain that actually handles the HTTP transport operations. + +4. - A specialty class that operates at the bottom of the handler chain class that handles HTTP transport operations with options that are specific to the object. + + If developers derive classes from and override the method, they must make sure that can get called concurrently by different threads. + + This is necessary since methods on can be called concurrently and need a guarantee of thread safety. So if a handler is assigned to an instance, the method of the handler may get called concurrently by the instance and needs to be thread safe. + ]]> @@ -174,13 +174,13 @@ to release both managed and unmanaged resources; to releases only unmanaged resources. Releases the unmanaged resources used by the and optionally disposes of the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. -When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - +When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + ]]> @@ -216,6 +216,7 @@ When the `disposing` parameter is `true`, this method releases all resources hel The HTTP response message. To be added. The method is not overridden in the derived class. + The cancellation token was canceled. This exception is stored into the returned task. @@ -256,16 +257,17 @@ When the `disposing` parameter is `true`, this method releases all resources hel Send an HTTP request as an asynchronous operation. The task object representing the asynchronous operation. - object will complete once the entire response including content is read. - - The method is used primarily by the system. This method is called by the system when one of the methods is called. Most apps will never call this method. - + object will complete once the entire response including content is read. + + The method is used primarily by the system. This method is called by the system when one of the methods is called. Most apps will never call this method. + ]]> The was . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/HttpMessageInvoker.xml b/xml/System.Net.Http/HttpMessageInvoker.xml index 6b9d871b465..de8df1770d9 100644 --- a/xml/System.Net.Http/HttpMessageInvoker.xml +++ b/xml/System.Net.Http/HttpMessageInvoker.xml @@ -38,13 +38,13 @@ A specialty class that allows applications to call the method on an HTTP handler chain. - and other message originators. - - Most applications that are connecting to a web site will use one of the methods on the class. - + and other message originators. + + Most applications that are connecting to a web site will use one of the methods on the class. + ]]> @@ -265,6 +265,7 @@ -or- If using custom not overriding method. + The cancellation token was canceled. This exception is stored into the returned task. @@ -305,16 +306,17 @@ Send an HTTP request as an asynchronous operation. The task object representing the asynchronous operation. - object will complete once the entire response including content is read. - - Most applications that are connecting to a web site will use one of the methods on the class. - + object will complete once the entire response including content is read. + + Most applications that are connecting to a web site will use one of the methods on the class. + ]]> The was . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/MessageProcessingHandler.xml b/xml/System.Net.Http/MessageProcessingHandler.xml index 70011c6f3a0..71b9458d38f 100644 --- a/xml/System.Net.Http/MessageProcessingHandler.xml +++ b/xml/System.Net.Http/MessageProcessingHandler.xml @@ -34,13 +34,13 @@ A base type for handlers which only do some small processing of request and/or response messages. - is useful if the handler doesn't require asynchronous operations, because operations on request and response messages are fast. - - The most common usage is to derive from this class and override the and methods. - + is useful if the handler doesn't require asynchronous operations, because operations on request and response messages are fast. + + The most common usage is to derive from this class and override the and methods. + ]]> @@ -159,13 +159,14 @@ Performs processing on each request sent to the server. The HTTP request message that was processed. - + The cancellation token was canceled. This exception is stored into the returned task. @@ -206,13 +207,14 @@ Perform processing on each response from the server. The HTTP response message that was processed. - + The cancellation token was canceled. This exception is stored into the returned task. @@ -245,6 +247,7 @@ Sends an HTTP request to the inner handler to send to the server. The HTTP response message. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -291,14 +294,15 @@ Sends an HTTP request to the inner handler to send to the server as an asynchronous operation. The task object representing the asynchronous operation. - method forwards the HTTP request to the inner handler to send to the server as an asynchronous operation. - + method forwards the HTTP request to the inner handler to send to the server as an asynchronous operation. + ]]> The was . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/MultipartContent.xml b/xml/System.Net.Http/MultipartContent.xml index f9e46a44184..00700ba3096 100644 --- a/xml/System.Net.Http/MultipartContent.xml +++ b/xml/System.Net.Http/MultipartContent.xml @@ -154,12 +154,12 @@ The boundary string for the multipart content. Creates a new instance of the class. To be added. - The was or an empty string. - - The was or contains only white space characters. - - -or- - + The was or an empty string. + + The was or contains only white space characters. + + -or- + The ends with a space character. The length of the was greater than 70. @@ -230,13 +230,14 @@ Serializes the HTTP content to a stream using the multipart/* encoding. The HTTP content stream that represents the multipart/* encoded HTTP content. - to use a custom stream that contains an array, with each HTTP content entity and its boundary encoded and serialized to a instance. ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -267,15 +268,15 @@ This method overrides Serializes the HTTP content to a stream using the multipart/* encoding as an asynchronous operation. The task object representing the asynchronous operation. - to use a custom stream that contains an array, with each HTTP content and its boundary encoded and serialized to a instance. - This operation will not block. The returned object will complete after all of the content has been written to the memory stream. - - Once the operation completes, the property on the returned task object contains the stream that represents the multipart/* encoded HTTP content. The returned stream can then be used to read the content using various stream APIs. - + This operation will not block. The returned object will complete after all of the content has been written to the memory stream. + + Once the operation completes, the property on the returned task object contains the stream that represents the multipart/* encoded HTTP content. The returned stream can then be used to read the content using various stream APIs. + ]]> @@ -308,17 +309,18 @@ This method overrides Serializes the HTTP content to a stream using the multipart/* encoding as an asynchronous operation. The task object representing the asynchronous operation. - to use a custom stream that contains an array, with each HTTP content and its boundary encoded and serialized to a instance. - This operation will not block. The returned object will complete after all of the content has been written to the memory stream. - - Once the operation completes, the property on the returned task object contains the stream that represents the multipart/* encoded HTTP content. The returned stream can then be used to read the content using various stream APIs. - + This operation will not block. The returned object will complete after all of the content has been written to the memory stream. + + Once the operation completes, the property on the returned task object contains the stream that represents the multipart/* encoded HTTP content. The returned stream can then be used to read the content using various stream APIs. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -357,13 +359,13 @@ This method overrides to release both managed and unmanaged resources; to releases only unmanaged resources. Releases the unmanaged resources used by the and optionally disposes of the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. -When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - +When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + ]]> @@ -404,15 +406,15 @@ When the `disposing` parameter is `true`, this method releases all resources hel Returns an enumerator that iterates through the collection of objects that get serialized using the multipart/* content type specification. An object that can be used to iterate through the collection. - @@ -474,6 +476,7 @@ When the `disposing` parameter is `true`, this method releases all resources hel The cancellation token to cancel the operation. Serializes the multipart HTTP content to a stream. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -525,11 +528,11 @@ When the `disposing` parameter is `true`, this method releases all resources hel Serialize the multipart HTTP content to a stream as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after all of the content has been serialized to the target stream. - + object will complete after all of the content has been serialized to the target stream. + ]]> @@ -566,13 +569,14 @@ When the `disposing` parameter is `true`, this method releases all resources hel Serialize the multipart HTTP content to a stream as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after all of the content has been serialized to the target stream. - + object will complete after all of the content has been serialized to the target stream. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -658,11 +662,11 @@ This member is an explicit interface member implementation. It can be used only if is a valid length; otherwise, . - method gives HTTP multipart content the ability to calculate the content length. This is useful for content types which are able to easily calculate the content length. If computing the content length is not possible or expensive (would require the system to buffer the whole content where the serialization would be expensive or require the system to allocate a lot of memory), this method can return `false`. If this method returns `false`, this implies that either chunked transfer is needed or the content must get buffered before being sent to the server. - + method gives HTTP multipart content the ability to calculate the content length. This is useful for content types which are able to easily calculate the content length. If computing the content length is not possible or expensive (would require the system to buffer the whole content where the serialization would be expensive or require the system to allocate a lot of memory), this method can return `false`. If this method returns `false`, this implies that either chunked transfer is needed or the content must get buffered before being sent to the server. + ]]> diff --git a/xml/System.Net.Http/MultipartFormDataContent.xml b/xml/System.Net.Http/MultipartFormDataContent.xml index cec0cbc2cab..b10779fedb5 100644 --- a/xml/System.Net.Http/MultipartFormDataContent.xml +++ b/xml/System.Net.Http/MultipartFormDataContent.xml @@ -34,11 +34,11 @@ Provides a container for content encoded using multipart/form-data MIME type. - type. All does is provide methods to add required Content-Disposition headers to content object added to the collection. - + type. All does is provide methods to add required Content-Disposition headers to content object added to the collection. + ]]> @@ -117,10 +117,10 @@ The boundary string for the multipart form data content. Creates a new instance of the class. To be added. - The was or contains only white space characters. - - -or- - + The was or contains only white space characters. + + -or- + The ends with a space character. The length of the was greater than 70. @@ -255,10 +255,10 @@ The file name for the HTTP content to add to the collection. Add HTTP content to a collection of objects that get serialized to multipart/form-data MIME type. To be added. - The was or contains only white space characters. - - -or- - + The was or contains only white space characters. + + -or- + The was or contains only white space characters. The was . @@ -295,13 +295,14 @@ Serialize and write the content provided in the constructor to an HTTP content stream as an asynchronous operation. The task object representing the asynchronous operation. - object completes, the whole content has been written to the `stream` parameter. - + object completes, the whole content has been written to the `stream` parameter. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/NSUrlSessionHandler.xml b/xml/System.Net.Http/NSUrlSessionHandler.xml index 96b3fc26767..0d9d04f243b 100644 --- a/xml/System.Net.Http/NSUrlSessionHandler.xml +++ b/xml/System.Net.Http/NSUrlSessionHandler.xml @@ -160,6 +160,7 @@ Sends an HTTP request as an asynchronous operation. The task object representing the asynchronous operation. This operation is does not block. It returns an instance of  to represent the asynchronous operation. When the operation completes, contains the response message. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/ReadOnlyMemoryContent.xml b/xml/System.Net.Http/ReadOnlyMemoryContent.xml index 5f77e54b3f8..78c6b90fbc3 100644 --- a/xml/System.Net.Http/ReadOnlyMemoryContent.xml +++ b/xml/System.Net.Http/ReadOnlyMemoryContent.xml @@ -88,6 +88,7 @@ To be added. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -151,6 +152,7 @@ The cancellation token to cancel the operation. Serializes the multipart HTTP content to a stream. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -221,6 +223,7 @@ To be added. To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/SocketsHttpHandler.xml b/xml/System.Net.Http/SocketsHttpHandler.xml index aa27641d6d5..60fb812a1a1 100644 --- a/xml/System.Net.Http/SocketsHttpHandler.xml +++ b/xml/System.Net.Http/SocketsHttpHandler.xml @@ -217,7 +217,7 @@ These configuration options are not available starting with .NET 5. ## Examples The following code example sets TCP `KeepAlive` on the underlying `Socket`. - + :::code language="csharp" source="~/snippets/csharp/System.Net.Http/SocketsHttpHandler/ConnectCallback/program.cs" id="Snippet1"::: @@ -323,7 +323,7 @@ The following code example sets TCP `KeepAlive` on the underlying `Socket`. When the default (system) proxy is used, gets or sets the credentials used to submit to the default proxy server for authentication. The credentials used to authenticate the user to an authenticating proxy. - is set to `true` and is set to `null`. @@ -619,7 +619,7 @@ Timeout must be greater than or equal to 1 second. Set to Gets or sets the maximum number of simultaneous TCP connections allowed to a single server. The maximum number of simultaneous TCP connections allowed to a single server. - Gets or sets the maximum amount of data that can be drained from responses in bytes. The maximum amount of data that can be drained from responses in bytes. - Gets or sets the maximum length, in kilobytes (1024 bytes), of the response headers. The maximum size of the header portion from the server response, in kilobytes. - . ]]> @@ -902,7 +902,7 @@ For example, if the value is 64, then 65,536 bytes are allowed for the maximum r Gets or sets the timespan to wait for data to be drained from responses. The timespan to wait for data to be drained from responses. - not overriding method. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1000,6 +1001,7 @@ Draining occurs when a request is cancelled or a response is disposed prior to f Sends an HTTP request as an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/StreamContent.xml b/xml/System.Net.Http/StreamContent.xml index dc1aeb35fb0..ce9711b62d6 100644 --- a/xml/System.Net.Http/StreamContent.xml +++ b/xml/System.Net.Http/StreamContent.xml @@ -80,8 +80,8 @@ The content used to initialize the . Creates a new instance of the class. - object calls on the provided object when is called. @@ -124,11 +124,11 @@ The object calls The size, in bytes, of the buffer for the . Creates a new instance of the class. - object calls on the provided object when is called. - + ]]> The was . @@ -163,6 +163,7 @@ The object calls Returns the HTTP stream as a read-only stream. The HTTP content stream. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -236,13 +237,13 @@ The object calls to release both managed and unmanaged resources; to releases only unmanaged resources. Releases the unmanaged resources used by the and optionally disposes of the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. -When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - +When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + ]]> @@ -278,6 +279,7 @@ When the `disposing` parameter is `true`, this method releases all resources hel The cancellation token to cancel the operation. Serializes the multipart HTTP content to a stream. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -323,11 +325,11 @@ When the `disposing` parameter is `true`, this method releases all resources hel Serialize the HTTP content to a stream as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after all of the content has been serialized to the target stream. - + object will complete after all of the content has been serialized to the target stream. + ]]> @@ -364,13 +366,14 @@ When the `disposing` parameter is `true`, this method releases all resources hel Serialize the HTTP content to a stream as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after all of the content has been serialized to the target stream. - + object will complete after all of the content has been serialized to the target stream. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -410,11 +413,11 @@ When the `disposing` parameter is `true`, this method releases all resources hel if is a valid length; otherwise, . - method gives HTTP stream content the ability to calculate the content length. This is useful for content types which are able to easily calculate the content length. If computing the content length is not possible or expensive (would require the system to buffer the whole content where the serialization would be expensive or require the system to allocate a lot of memory), this method can return `false`. If this method returns `false`, this implies that either chunked transfer is needed or the content must get buffered before being sent to the server. - + method gives HTTP stream content the ability to calculate the content length. This is useful for content types which are able to easily calculate the content length. If computing the content length is not possible or expensive (would require the system to buffer the whole content where the serialization would be expensive or require the system to allocate a lot of memory), this method can return `false`. If this method returns `false`, this implies that either chunked transfer is needed or the content must get buffered before being sent to the server. + ]]> diff --git a/xml/System.Net.Http/StringContent.xml b/xml/System.Net.Http/StringContent.xml index f609b8167ed..2fdd1e8360f 100644 --- a/xml/System.Net.Http/StringContent.xml +++ b/xml/System.Net.Http/StringContent.xml @@ -80,11 +80,11 @@ The content used to initialize the . Creates a new instance of the class. - created defaults to text/plain. - + created defaults to text/plain. + ]]> @@ -150,11 +150,11 @@ The encoding to use for the content. Creates a new instance of the class. - created defaults to text/plain. - + created defaults to text/plain. + ]]> @@ -259,13 +259,14 @@ Serialize and write the string provided in the constructor to an HTTP content stream as an asynchronous operation. The task object representing the asynchronous operation. - object completes, the whole string has been written to the `stream` parameter. - + object completes, the whole string has been written to the `stream` parameter. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Http/WinHttpHandler.xml b/xml/System.Net.Http/WinHttpHandler.xml index 83ae034b3fc..85fa7a39c6f 100644 --- a/xml/System.Net.Http/WinHttpHandler.xml +++ b/xml/System.Net.Http/WinHttpHandler.xml @@ -26,16 +26,16 @@ Handles messages based on the WinHTTP interface of Windows. This class is intended for use in server environments. - is similar to other existing classes such as . provides a handler underneath an instance and is used to send HTTP requests out to a server and receive server responses. The implementation supports HTTP versions up to HTTP/2. - - is designed to be used primarily in server environments by ASP.NET Core and other .NET applications that communicate with HTTP servers. also provides developers with more granular control over the application's HTTP communication than the class. This allows developers to implement more advanced HTTP scenarios or modify system defaults (for example, proxy settings, timeouts, and server SSL certificate validation). - - is not intended to be a replacement for . Instead, it's a more advanced version that's provided for scenarios where is insufficient. is implemented as a thin wrapper on the WinHTTP interface of Windows and is only supported on Windows systems. - + is similar to other existing classes such as . provides a handler underneath an instance and is used to send HTTP requests out to a server and receive server responses. The implementation supports HTTP versions up to HTTP/2. + + is designed to be used primarily in server environments by ASP.NET Core and other .NET applications that communicate with HTTP servers. also provides developers with more granular control over the application's HTTP communication than the class. This allows developers to implement more advanced HTTP scenarios or modify system defaults (for example, proxy settings, timeouts, and server SSL certificate validation). + + is not intended to be a replacement for . Instead, it's a more advanced version that's provided for scenarios where is insufficient. is implemented as a thin wrapper on the WinHTTP interface of Windows and is only supported on Windows systems. + When using a chain of multiple handlers, should be at the bottom of the chain. This class is also available for use in Desktop apps by installing it as a NuGet package. For more information, see [System.Net.Http.WinHttpHandler NuGet package](https://www.nuget.org/packages/System.Net.Http.WinHttpHandler/). @@ -100,11 +100,11 @@ Starting in .NET 5, is no longer included Gets or sets the type of decompression method used by the handler for automatic decompression of the HTTP content response. To be added. - @@ -138,12 +138,12 @@ Starting in .NET 5, is no longer included to follow HTTP redirection responses; otherwise, . The default is . - @@ -207,11 +207,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets a value that indicates if the certificate is automatically picked from the certificate store or if the caller is allowed to pass in a specific client certificate. To be added. - . - + . + ]]> @@ -244,11 +244,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets a collection of client authentication SSL certificates that are used for client authentication by the handler if the property is set to . To be added. - @@ -282,11 +282,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the managed cookie container object. This property is only used when the property is set to UseSpecifiedCookieContainer. Otherwise, the method will throw an exception. To be added. - @@ -319,11 +319,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets a value that indicates how cookies should be managed and used. Developers can choose to ignore cookies, allow the handler to automatically manage them or manually handle them using a object. To be added. - . If this value is set to , then a container object must be initialized and assigned to the property. Otherwise, an exception will be thrown when trying to send a request. - + . If this value is set to , then a container object must be initialized and assigned to the property. Otherwise, an exception will be thrown when trying to send a request. + ]]> @@ -357,11 +357,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the credentials used to authenticate the user to an authenticating proxy. To be added. - . - + . + ]]> @@ -463,11 +463,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the maximum number of allowed HTTP redirects. The maximum number of allowed HTTP redirects. - is set to `true`. - + is set to `true`. + ]]> @@ -500,11 +500,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the maximum number of TCP connections allowed to a single server. The maximum number of TCP connections allowed to a single server. - @@ -537,11 +537,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the maximum amount of data that can be drained from responses in bytes. The maximum amount of data that can be drained from responses in bytes. - @@ -574,11 +574,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the maximum size of the header portion from the server response in bytes. The maximum size of the header portion from the server response in bytes. - @@ -611,11 +611,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets a value that indicates whether the handler sends an Authorization header with the request. To be added. - @@ -679,11 +679,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the custom proxy when the property is set to use a custom proxy. To be added. - @@ -716,11 +716,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the timeout for receiving the data portion of a response from the server. The timeout for receiving the data portion of a response from the server. - @@ -753,11 +753,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the timeout for receiving the headers of a response from the server. The timeout for receiving the headers of a response from the server. - @@ -796,6 +796,7 @@ When this property is set to `true`, all HTTP redirect responses from the server Sends an HTTP request as an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -826,11 +827,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the timeout for sending a request. The timeout for sending a request. - @@ -864,11 +865,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets a callback method to validate the server certificate. This callback is part of the SSL handshake. The callback should return if the server certificate is considered valid and the request should be sent. Otherwise, return . - @@ -902,11 +903,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the credentials to be used by the client to authenticate to the server. The credentials to be used by the client to authenticate to the server. - @@ -939,11 +940,11 @@ When this property is set to `true`, all HTTP redirect responses from the server Gets or sets the collection of TLS/SSL protocols supported by the client. The collection of TLS/SSL protocols supported by the client. - @@ -1072,11 +1073,11 @@ Only supported on Windows 10 version 2004 or newer. Gets or sets the proxy setting. This property can be set to disable the proxy, use a custom proxy, or use the proxy settings of WinHTTP or WinInet on the machine. To be added. - diff --git a/xml/System.Net.Mail/SmtpClient.xml b/xml/System.Net.Mail/SmtpClient.xml index fbeca554a06..58ec0c482ea 100644 --- a/xml/System.Net.Mail/SmtpClient.xml +++ b/xml/System.Net.Mail/SmtpClient.xml @@ -56,11 +56,11 @@ Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP). The type is obsolete on some platforms and not recommended on others; for more information, see the Remarks section. - [!IMPORTANT] > We don't recommend that you use the `SmtpClient` class for new development because `SmtpClient` doesn't support many modern protocols. Use [MailKit](https://github.com/jstedfast/MailKit) or other libraries instead. For more information, see [SmtpClient shouldn't be used](https://github.com/dotnet/platform-compat/blob/master/docs/DE0005.md) on GitHub. @@ -71,54 +71,54 @@ The `SmtpClient` class is obsolete in Xamarin. However: - It is present and can be used in .NET Framework 4 through .NET Framework 4.8. - It is usable in .NET Core, but its use isn't recommended. -The classes shown in the following table are used to construct email messages that can be sent using . - -|Class|Description| -|-----------|-----------------| -||Represents file attachments. This class allows you to attach files, streams, or text to an email message.| -||Represents the email address of the sender and recipients.| -||Represents an email message.| - - To construct and send an email message by using , you must specify the following information: - -- The SMTP host server that you use to send email. See the and properties. - -- Credentials for authentication, if required by the SMTP server. See the property. - -- The email address of the sender. See the and methods that take a `from` parameter. Also see the property. - -- The email address or addresses of the recipients. See the and methods that take a `recipient` parameter. Also see the property. - -- The message content. See the and methods that take a `body` parameter. Also see the property. - - To include an attachment with an email message, first create the attachment by using the class, and then add it to the message by using the property. Depending on the email reader used by the recipients and the file type of the attachment, some recipients might not be able to read the attachment. For clients that cannot display the attachment in its original form, you can specify alternate views by using the property. - - In .NET Framework, you can use the application or machine configuration files to specify default host, port, and credentials values for all objects. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). .NET Core does not support setting defaults. As a workaround, you must set the relevant properties on directly. - - To send the email message and block while waiting for the email to be transmitted to the SMTP server, use one of the synchronous methods. To allow your program's main thread to continue executing while the email is transmitted, use one of the asynchronous methods. The event is raised when a operation completes. To receive this event, you must add a delegate to . The delegate must reference a callback method that handles notification of events. To cancel an asynchronous email transmission, use the method. - +The classes shown in the following table are used to construct email messages that can be sent using . + +|Class|Description| +|-----------|-----------------| +||Represents file attachments. This class allows you to attach files, streams, or text to an email message.| +||Represents the email address of the sender and recipients.| +||Represents an email message.| + + To construct and send an email message by using , you must specify the following information: + +- The SMTP host server that you use to send email. See the and properties. + +- Credentials for authentication, if required by the SMTP server. See the property. + +- The email address of the sender. See the and methods that take a `from` parameter. Also see the property. + +- The email address or addresses of the recipients. See the and methods that take a `recipient` parameter. Also see the property. + +- The message content. See the and methods that take a `body` parameter. Also see the property. + + To include an attachment with an email message, first create the attachment by using the class, and then add it to the message by using the property. Depending on the email reader used by the recipients and the file type of the attachment, some recipients might not be able to read the attachment. For clients that cannot display the attachment in its original form, you can specify alternate views by using the property. + + In .NET Framework, you can use the application or machine configuration files to specify default host, port, and credentials values for all objects. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). .NET Core does not support setting defaults. As a workaround, you must set the relevant properties on directly. + + To send the email message and block while waiting for the email to be transmitted to the SMTP server, use one of the synchronous methods. To allow your program's main thread to continue executing while the email is transmitted, use one of the asynchronous methods. The event is raised when a operation completes. To receive this event, you must add a delegate to . The delegate must reference a callback method that handles notification of events. To cancel an asynchronous email transmission, use the method. + > [!NOTE] -> If there is an email transmission in progress and you call or again, you will receive an . - - The connection established by the current instance of the class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers. - - The class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the object and it should be cleaned up. - - When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client. - - The class has no `Finalize` method, so an application must call to explicitly free up resources. The method iterates through all established connections to the SMTP server specified in the property and sends a QUIT message followed by gracefully ending the TCP connection. The method also releases the unmanaged resources used by the and optionally disposes of the managed resources. - - Call when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. - - - -## Examples - The following code example demonstrates sending an email message asynchronously. - +> If there is an email transmission in progress and you call or again, you will receive an . + + The connection established by the current instance of the class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers. + + The class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the object and it should be cleaned up. + + When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client. + + The class has no `Finalize` method, so an application must call to explicitly free up resources. The method iterates through all established connections to the SMTP server specified in the property and sends a QUIT message followed by gracefully ending the TCP connection. The method also releases the unmanaged resources used by the and optionally disposes of the managed resources. + + Call when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + + + +## Examples + The following code example demonstrates sending an email message asynchronously. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclMailASync/cpp/mailasync.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/MailAddress/.ctor/mailasync.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclMailASync/vb/mailasync.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclMailASync/vb/mailasync.vb" id="Snippet1"::: + ]]> @@ -169,21 +169,21 @@ The classes shown in the following table are used to construct email messages th Initializes a new instance of the class by using configuration file settings. - , , and properties for the new by using the settings in the application or machine configuration files. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). - - - -## Examples - The following code example demonstrates sending an email message. - + , , and properties for the new by using the settings in the application or machine configuration files. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). + + + +## Examples + The following code example demonstrates sending an email message. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLMailSync/CPP/NclMailSync.cpp" id="Snippet4"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet4"::: - - For an example of the \ node in the application or machine configuration file, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). - + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet4"::: + + For an example of the \ node in the application or machine configuration file, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). + ]]> @@ -224,21 +224,21 @@ The classes shown in the following table are used to construct email messages th A that contains the name or IP address of the host computer used for SMTP transactions. Initializes a new instance of the class that sends email by using the specified SMTP server. - property. The and properties are initialized by using the settings in the application or machine configuration files. If `host` is `null` or equal to , is initialized using the settings in the application or machine configuration files. - - For more information about using the application and machine configuration files, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). If information is specified using constructors or properties, this information overrides the configuration file settings. - - - -## Examples - The following code example demonstrates calling this constructor. - + property. The and properties are initialized by using the settings in the application or machine configuration files. If `host` is `null` or equal to , is initialized using the settings in the application or machine configuration files. + + For more information about using the application and machine configuration files, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). If information is specified using constructors or properties, this information overrides the configuration file settings. + + + +## Examples + The following code example demonstrates calling this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLMailSync/CPP/NclMailSync.cpp" id="Snippet3"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet3"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet3"::: + ]]> @@ -281,21 +281,21 @@ The classes shown in the following table are used to construct email messages th An greater than zero that contains the port to be used on . Initializes a new instance of the class that sends email by using the specified SMTP server and port. - and properties, respectively. If `host` is `null` or equal to , is initialized using the settings in the application or machine configuration files. If `port` is zero, is initialized using the settings in the application or machine configuration files. The property is initialized using the settings in the application or machine configuration files. - - For more information about using the application and machine configuration files, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). If information is specified using constructors or properties, this information overrides the configuration file settings. - - - -## Examples - The following code example demonstrates calling this constructor. - + and properties, respectively. If `host` is `null` or equal to , is initialized using the settings in the application or machine configuration files. If `port` is zero, is initialized using the settings in the application or machine configuration files. The property is initialized using the settings in the application or machine configuration files. + + For more information about using the application and machine configuration files, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). If information is specified using constructors or properties, this information overrides the configuration file settings. + + + +## Examples + The following code example demonstrates calling this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLMailSync/CPP/NclMailSync.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet1"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet1"::: + ]]> @@ -343,21 +343,21 @@ The classes shown in the following table are used to construct email messages th Specify which certificates should be used to establish the Secure Sockets Layer (SSL) connection. An , holding one or more client certificates. The default value is derived from the mail configuration attributes in a configuration file. - [!NOTE] -> The Framework caches SSL sessions as they are created and attempts to reuse a cached session for a new request, if possible. When attempting to reuse an SSL session, the Framework uses the first element of (if there is one), or tries to reuse an anonymous sessions if is empty. - - - -## Examples - The following code example establishes an SSL connection with the SMTP server and uses the connection to send an email. - - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/SmtpClient/ClientCertificates/mail.cs" id="Snippet1"::: - +> The Framework caches SSL sessions as they are created and attempts to reuse a cached session for a new request, if possible. When attempting to reuse an SSL session, the Framework uses the first element of (if there is one), or tries to reuse an anonymous sessions if is empty. + + + +## Examples + The following code example establishes an SSL connection with the SMTP server and uses the connection to send an email. + + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/SmtpClient/ClientCertificates/mail.cs" id="Snippet1"::: + ]]> MailSettings Element (Network Settings) @@ -399,24 +399,24 @@ The classes shown in the following table are used to construct email messages th Gets or sets the credentials used to authenticate the sender. An that represents the credentials to use for authentication; or if no credentials have been specified. - to `true` instead of setting this property. If the property is set to `false,` then the value set in the property will be used for the credentials when connecting to the server. If the property is set to `false` and the property has not been set, then mail is sent to the server anonymously. - - Credentials information can also be specified using the application and machine configuration files. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). If information is specified using the property, this information overrides the configuration file settings. - + to `true` instead of setting this property. If the property is set to `false,` then the value set in the property will be used for the credentials when connecting to the server. If the property is set to `false` and the property has not been set, then mail is sent to the server anonymously. + + Credentials information can also be specified using the application and machine configuration files. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). If information is specified using the property, this information overrides the configuration file settings. + > [!CAUTION] -> If you provide credentials for basic authentication, they are sent to the server in clear text. This can present a security issue because your credentials can be seen, and then used by others. - - - -## Examples - The following code example demonstrates setting the credentials used to send an email. - +> If you provide credentials for basic authentication, they are sent to the server in clear text. This can present a security issue because your credentials can be seen, and then used by others. + + + +## Examples + The following code example demonstrates setting the credentials used to send an email. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLMailSync/CPP/NclMailSync.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet1"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet1"::: + ]]> You cannot change the value of this property when an email is being sent. @@ -503,19 +503,19 @@ The classes shown in the following table are used to construct email messages th Specifies how outgoing email messages will be handled. An that indicates how email messages are delivered. - for later delivery by another application. - - The default value for this property can also be set in a machine or application configuration file. Any changes made to the property override the configuration file settings. - + for later delivery by another application. + + The default value for this property can also be set in a machine or application configuration file. Any changes made to the property override the configuration file settings. + ]]> @@ -533,17 +533,17 @@ The classes shown in the following table are used to construct email messages th Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the class. - class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers. - - The class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the object and it should be cleaned up. - - When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client. - - The methods iterates through all established connections and send a QUIT message to each SMTP server, followed by gracefully ending the TCP connection. These methods also release the unmanaged resources used by the and optionally dispose of the managed resources. - + class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers. + + The class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the object and it should be cleaned up. + + When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client. + + The methods iterates through all established connections and send a QUIT message to each SMTP server, followed by gracefully ending the TCP connection. These methods also release the unmanaged resources used by the and optionally dispose of the managed resources. + ]]> @@ -585,28 +585,28 @@ The classes shown in the following table are used to construct email messages th Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the class. - class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers. - - The class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the object and it should be cleaned up. - - When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client. - - Calling the method on a object that is executing an asynchronous operation will cancel the send operation as though the method had been called. - - The class has no `Finalize` method. So an application must call to explicitly free up resources. - - The method iterates through all established connections to the SMTP server specified in the property and sends a QUIT message followed by gracefully ending the TCP connection. The method also releases the unmanaged resources used by the underlying . - - Call when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. - - For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers. + + The class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the object and it should be cleaned up. + + When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client. + + Calling the method on a object that is executing an asynchronous operation will cancel the send operation as though the method had been called. + + The class has no `Finalize` method. So an application must call to explicitly free up resources. + + The method iterates through all established connections to the SMTP server specified in the property and sends a QUIT message followed by gracefully ending the TCP connection. The method also releases the unmanaged resources used by the underlying . + + Call when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + + For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + > [!NOTE] -> Always call before you release your last reference to the . Otherwise, the resources it is using will not be freed so the garbage collector can reclaim the memory. - +> Always call before you release your last reference to the . Otherwise, the resources it is using will not be freed so the garbage collector can reclaim the memory. + ]]> @@ -655,28 +655,28 @@ The classes shown in the following table are used to construct email messages th to release both managed and unmanaged resources; to releases only unmanaged resources. Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, releases all resources used by the current instance of the class, and optionally disposes of the managed resources. - class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers. - - The class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the object and it should be cleaned up. - - When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client. - - Calling the method on a object that is executing an asynchronous operation will cancel the send operation as though the method had been called. - - The class has no `Finalize` method. So an application must call to explicitly free up resources. - - The method iterates through all established connections to the SMTP server specified in the property and sends a QUIT message followed by gracefully ending the TCP connection. The method also releases the unmanaged resources used by the and optionally disposes of the managed resources. - - Call when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. - - For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers. + + The class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the object and it should be cleaned up. + + When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client. + + Calling the method on a object that is executing an asynchronous operation will cancel the send operation as though the method had been called. + + The class has no `Finalize` method. So an application must call to explicitly free up resources. + + The method iterates through all established connections to the SMTP server specified in the property and sends a QUIT message followed by gracefully ending the TCP connection. The method also releases the unmanaged resources used by the and optionally disposes of the managed resources. + + Call when you are finished using the . The method leaves the in an unusable state. After calling , you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + + For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + > [!NOTE] -> Always call before you release your last reference to the . Otherwise, the resources it is using will not be freed so the garbage collector can reclaim the memory. - +> Always call before you release your last reference to the . Otherwise, the resources it is using will not be freed so the garbage collector can reclaim the memory. + ]]> @@ -717,29 +717,29 @@ The classes shown in the following table are used to construct email messages th if the uses SSL; otherwise, . The default is . - property specifies whether SSL is used to access the specified SMTP mail server. - - The default value for this property can also be set in a machine or application configuration file. Any changes made to the property override the configuration file settings. - - The class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information. - - An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported. - - You can use to specify which client certificates should be used to establish the SSL connection. The allows you to reject the certificate provided by the SMTP server. The property allows you to specify the version of the SSL protocol to use. - + property specifies whether SSL is used to access the specified SMTP mail server. + + The default value for this property can also be set in a machine or application configuration file. Any changes made to the property override the configuration file settings. + + The class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information. + + An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported. + + You can use to specify which client certificates should be used to establish the SSL connection. The allows you to reject the certificate provided by the SMTP server. The property allows you to specify the version of the SSL protocol to use. + > [!NOTE] -> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . - - - -## Examples - The following code example establishes an SSL connection with the SMTP server and uses the connection to send an email. - - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/SmtpClient/ClientCertificates/mail.cs" id="Snippet1"::: - +> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . + + + +## Examples + The following code example establishes an SSL connection with the SMTP server and uses the connection to send an email. + + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/SmtpClient/ClientCertificates/mail.cs" id="Snippet1"::: + ]]> @@ -792,21 +792,21 @@ The classes shown in the following table are used to construct email messages th Gets or sets the name or IP address of the host used for SMTP transactions. A that contains the name or IP address of the computer to use for SMTP transactions. - property can also be set using constructors or the application or machine configuration file. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). - - If information is specified using this property, this information overrides the configuration file settings. - - - -## Examples - The following code example demonstrates sending an email message by using the host and port specified in an application configuration file. - + property can also be set using constructors or the application or machine configuration file. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). + + If information is specified using this property, this information overrides the configuration file settings. + + + +## Examples + The following code example demonstrates sending an email message by using the host and port specified in an application configuration file. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLMailSync/CPP/NclMailSync.cpp" id="Snippet7"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet7"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet7"::: + ]]> The value specified for a set operation is . @@ -859,13 +859,13 @@ The classes shown in the following table are used to construct email messages th An that contains event data. Raises the event. - class can override the method to perform additional tasks when the event occurs. - - also allows derived classes to handle without attaching a delegate. This is the preferred technique for handling in a derived class. - + class can override the method to perform additional tasks when the event occurs. + + also allows derived classes to handle without attaching a delegate. This is the preferred technique for handling in a derived class. + ]]> @@ -919,13 +919,13 @@ The classes shown in the following table are used to construct email messages th Gets or sets the folder where applications save mail messages to be processed by the local SMTP server. A that specifies the pickup directory for mail messages. - property override the configuration file settings. - + property override the configuration file settings. + ]]> @@ -975,19 +975,19 @@ The classes shown in the following table are used to construct email messages th Gets or sets the port used for SMTP transactions. An that contains the port number on the SMTP host. The default value is 25. - property can also be set using constructors or the application or machine configuration file. For more information about using configuration files, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). If information is specified using this property, this information overrides the configuration file settings. - - - -## Examples - The following code example demonstrates sending an email message by using the host and port specified in an application configuration file. - + property can also be set using constructors or the application or machine configuration file. For more information about using configuration files, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). If information is specified using this property, this information overrides the configuration file settings. + + + +## Examples + The following code example demonstrates sending an email message by using the host and port specified in an application configuration file. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLMailSync/CPP/NclMailSync.cpp" id="Snippet7"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet7"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet7"::: + ]]> The value specified for a set operation is less than or equal to zero. @@ -1049,74 +1049,74 @@ The classes shown in the following table are used to construct email messages th A that contains the message to send. Sends the specified message to an SMTP server for delivery. - property to ensure that the method returns after a specified amount of time elapses. - - Before calling this method, the and properties must be set either through the configuration files by setting the relevant properties, or by passing this information into the constructor. - - You cannot call this method if there is a message being sent asynchronously. - - If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the or properties. - - If you receive an exception, check the property to find the reason the operation failed. The can also contain an inner exception that indicates the reason the operation failed. - + property to ensure that the method returns after a specified amount of time elapses. + + Before calling this method, the and properties must be set either through the configuration files by setting the relevant properties, or by passing this information into the constructor. + + You cannot call this method if there is a message being sent asynchronously. + + If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the or properties. + + If you receive an exception, check the property to find the reason the operation failed. The can also contain an inner exception that indicates the reason the operation failed. + When sending email using to multiple recipients and the SMTP server accepts some recipients as valid and rejects others, sends email to the accepted recipients and then a is thrown (or a if only one recipient is rejected). A contains a list of the recipients that were rejected. - + > [!NOTE] -> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . - - - -## Examples - The following code example demonstrates using this method. - +> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . + + + +## Examples + The following code example demonstrates using this method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLMailSync/CPP/NclMailSync.cpp" id="Snippet2"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet2"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet2"::: + ]]> is . - This has another send operation already in progress. - - -or- - - is . - - -or- - - There are no recipients specified in , , and properties. - - -or- - - property is set to and is . - - -or- - - property is set to and is equal to the empty string (""). - - -or- - + This has another send operation already in progress. + + -or- + + is . + + -or- + + There are no recipients specified in , , and properties. + + -or- + + property is set to and is . + + -or- + + property is set to and is equal to the empty string (""). + + -or- + property is set to and is zero, a negative number, or greater than 65,535. This object has been disposed. - The connection to the SMTP server failed. - - -or- - - Authentication failed. - - -or- - - The operation timed out. - - -or- - - is set to but the property is set to or . - - -or- - + The connection to the SMTP server failed. + + -or- + + Authentication failed. + + -or- + + The operation timed out. + + -or- + + is set to but the property is set to or . + + -or- + is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. The could not be delivered to one of the recipients in , , or . The could not be delivered to two or more of the recipients in , , or . @@ -1174,68 +1174,68 @@ The classes shown in the following table are used to construct email messages th A that contains the message body. Sends the specified email message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using objects. - property to ensure that the method returns after a specified amount of time elapses. - - Before calling this method, the and properties must be set either through the configuration files by setting the relevant properties, or by passing this information into the constructor. - - You cannot call this method if there is a message being sent asynchronously. - - If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the or properties. - - If you receive an exception, check the property to find the reason the operation failed. The can also contain an inner exception that indicates the reason the operation failed. + property to ensure that the method returns after a specified amount of time elapses. + + Before calling this method, the and properties must be set either through the configuration files by setting the relevant properties, or by passing this information into the constructor. + + You cannot call this method if there is a message being sent asynchronously. + + If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the or properties. + + If you receive an exception, check the property to find the reason the operation failed. The can also contain an inner exception that indicates the reason the operation failed. When sending email using to multiple recipients and the SMTP server accepts some recipients as valid and rejects others, sends email to the accepted recipients and then a is thrown (or a if only one recipient is rejected). A contains a list of the recipients that were rejected. - + > [!NOTE] -> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . - +> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . + ]]> - is . - - -or- - + is . + + -or- + is . - is . - - -or- - + is . + + -or- + is . - This has another send operation already in progress. - - -or- - - property is set to and is . - - -or- - - property is set to and is equal to the empty string (""). - - -or- - + This has another send operation already in progress. + + -or- + + property is set to and is . + + -or- + + property is set to and is equal to the empty string (""). + + -or- + property is set to and is zero, a negative number, or greater than 65,535. This object has been disposed. - The connection to the SMTP server failed. - - -or- - - Authentication failed. - - -or- - - The operation timed out. - - -or- - - is set to but the property is set to or . - - -or- - + The connection to the SMTP server failed. + + -or- + + Authentication failed. + + -or- + + The operation timed out. + + -or- + + is set to but the property is set to or . + + -or- + is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. The could not be delivered to one of the recipients in , , or . The could not be delivered to two or more of the recipients in , , or . @@ -1292,85 +1292,85 @@ The classes shown in the following table are used to construct email messages th A user-defined object that is passed to the method invoked when the asynchronous operation completes. Sends the specified email message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes. - event. You can cancel a operation by calling the method. - - After calling , you must wait for the email transmission to complete before attempting to send another email message using or . - - Before calling this method, the and must be set through the configuration files by setting the relevant properties, or by passing this information into the constructor. - - If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the or properties. - - If you receive an exception, check the property to find the reason the operation failed. The can also contain an inner exception that indicates the reason the operation failed. - - When sending email using to multiple recipients, if the SMTP server accepts some recipients as valid and rejects others, a is thrown with a for the inner exception. If this occurs, fails to send email to any of the recipients. - - Your application can detect a server certificate validation error by examining the property passed into the delegate. - - The property does not have any effect on a call. - - To send mail and block while it is transmitted to the SMTP server, use one of the methods. - + event. You can cancel a operation by calling the method. + + After calling , you must wait for the email transmission to complete before attempting to send another email message using or . + + Before calling this method, the and must be set through the configuration files by setting the relevant properties, or by passing this information into the constructor. + + If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the or properties. + + If you receive an exception, check the property to find the reason the operation failed. The can also contain an inner exception that indicates the reason the operation failed. + + When sending email using to multiple recipients, if the SMTP server accepts some recipients as valid and rejects others, a is thrown with a for the inner exception. If this occurs, fails to send email to any of the recipients. + + Your application can detect a server certificate validation error by examining the property passed into the delegate. + + The property does not have any effect on a call. + + To send mail and block while it is transmitted to the SMTP server, use one of the methods. + > [!NOTE] -> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . - - - -## Examples - The following code example demonstrates calling this method. - +> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . + + + +## Examples + The following code example demonstrates calling this method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclMailASync/cpp/mailasync.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/MailAddress/.ctor/mailasync.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclMailASync/vb/mailasync.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclMailASync/vb/mailasync.vb" id="Snippet1"::: + ]]> - is . - - -or- - + is . + + -or- + is . - This has another send operation already in progress. - - -or- - - There are no recipients specified in , , and properties. - - -or- - - property is set to and is . - - -or- - - property is set to and is equal to the empty string (""). - - -or- - + This has another send operation already in progress. + + -or- + + There are no recipients specified in , , and properties. + + -or- + + property is set to and is . + + -or- + + property is set to and is equal to the empty string (""). + + -or- + property is set to and is zero, a negative number, or greater than 65,535. This object has been disposed. - The connection to the SMTP server failed. - - -or- - - Authentication failed. - - -or- - - The operation timed out. - - -or- - - is set to but the property is set to or . - - -or- - - is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. - - -or- - + The connection to the SMTP server failed. + + -or- + + Authentication failed. + + -or- + + The operation timed out. + + -or- + + is set to but the property is set to or . + + -or- + + is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. + + -or- + The could not be delivered to one or more of the recipients in , , or . The could not be delivered to one of the recipients in , , or . The could not be delivered to two or more of the recipients in , , or . @@ -1430,78 +1430,78 @@ The classes shown in the following table are used to construct email messages th A user-defined object that is passed to the method invoked when the asynchronous operation completes. Sends an email message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using objects. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes. - event. You can cancel a operation by calling the method. - - After calling , you must wait for the email transmission to complete before attempting to send another email message using or . - - Before calling this method, the and properties must be set either through the configuration files or by setting the properties or passing this information into the constructor. - - If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the or property. - - If you receive an exception, check the property to find the reason the operation failed. The can also contain an inner exception that indicates the reason the operation failed. - - When sending email using to multiple recipients, if the SMTP server accepts some recipients as valid and rejects others, a is thrown with a for the inner exception. If this occurs, fails to send email to any of the recipients. - - Your application can detect a server certificate validation error by examining the property passed into the delegate. - - The property does not have any effect on a call. - - To send mail and block while it is transmitted to the SMTP server, use one of the methods. - + event. You can cancel a operation by calling the method. + + After calling , you must wait for the email transmission to complete before attempting to send another email message using or . + + Before calling this method, the and properties must be set either through the configuration files or by setting the properties or passing this information into the constructor. + + If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the or property. + + If you receive an exception, check the property to find the reason the operation failed. The can also contain an inner exception that indicates the reason the operation failed. + + When sending email using to multiple recipients, if the SMTP server accepts some recipients as valid and rejects others, a is thrown with a for the inner exception. If this occurs, fails to send email to any of the recipients. + + Your application can detect a server certificate validation error by examining the property passed into the delegate. + + The property does not have any effect on a call. + + To send mail and block while it is transmitted to the SMTP server, use one of the methods. + > [!NOTE] -> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . - +> If the property is set to `true`, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the or methods will throw an . + ]]> - is . - - -or- - + is . + + -or- + is . - is . - - -or- - + is . + + -or- + is . - This has a call in progress. - - -or- - - property is set to and is . - - -or- - - property is set to and is equal to the empty string (""). - - -or- - + This has a call in progress. + + -or- + + property is set to and is . + + -or- + + property is set to and is equal to the empty string (""). + + -or- + property is set to and is zero, a negative number, or greater than 65,535. This object has been disposed. - The connection to the SMTP server failed. - - -or- - - Authentication failed. - - -or- - - The operation timed out. - - -or- - - is set to but the property is set to or . - - -or- - - is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. - - -or- - + The connection to the SMTP server failed. + + -or- + + Authentication failed. + + -or- + + The operation timed out. + + -or- + + is set to but the property is set to or . + + -or- + + is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. + + -or- + The message could not be delivered to one or more of the recipients in . The could not be delivered to one of the recipients in , , or . The could not be delivered to two or more of the recipients in , , or . @@ -1542,20 +1542,20 @@ The classes shown in the following table are used to construct email messages th Cancels an asynchronous operation to send an email message. - method to cancel a pending operation. If there is mail waiting to be sent, this method releases resources used to store the mail. If there is no mail waiting to be sent, this method does nothing. - - - -## Examples - The following code example demonstrates sending an email message asynchronously. The user has the option to cancel the mail if it has not been sent. - + method to cancel a pending operation. If there is mail waiting to be sent, this method releases resources used to store the mail. If there is no mail waiting to be sent, this method does nothing. + + + +## Examples + The following code example demonstrates sending an email message asynchronously. The user has the option to cancel the mail if it has not been sent. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclMailASync/cpp/mailasync.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/MailAddress/.ctor/mailasync.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclMailASync/vb/mailasync.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclMailASync/vb/mailasync.vb" id="Snippet1"::: + ]]> This object has been disposed. @@ -1597,22 +1597,22 @@ The classes shown in the following table are used to construct email messages th Occurs when an asynchronous email send operation completes. - event is raised each time an email message is sent asynchronously when the send operation completes. To send an email message asynchronously, use the methods. - - is the delegate for . The class provides the event handler with event data. - - - -## Examples - The following code example demonstrates sending an email message asynchronously. - + event is raised each time an email message is sent asynchronously when the send operation completes. To send an email message asynchronously, use the methods. + + is the delegate for . The class provides the event handler with event data. + + + +## Examples + The following code example demonstrates sending an email message asynchronously. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclMailASync/cpp/mailasync.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/MailAddress/.ctor/mailasync.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclMailASync/vb/mailasync.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclMailASync/vb/mailasync.vb" id="Snippet1"::: + ]]> @@ -1665,53 +1665,53 @@ The classes shown in the following table are used to construct email messages th Sends the specified message to an SMTP server for delivery as an asynchronous operation. The task object representing the asynchronous operation. - object will complete once the message has been sent. ]]> is . - This has another send operation already in progress. - - -or- - - There are no recipients specified in , , and properties. - - -or- - - property is set to and is . - - -or- - - property is set to and is equal to the empty string (""). - - -or- - + This has another send operation already in progress. + + -or- + + There are no recipients specified in , , and properties. + + -or- + + property is set to and is . + + -or- + + property is set to and is equal to the empty string (""). + + -or- + property is set to and is zero, a negative number, or greater than 65,535. This object has been disposed. - The connection to the SMTP server failed. - - -or- - - Authentication failed. - - -or- - - The operation timed out. - - -or- - - is set to but the property is set to or . - - -or- - - is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. - - -or- - + The connection to the SMTP server failed. + + -or- + + Authentication failed. + + -or- + + The operation timed out. + + -or- + + is set to but the property is set to or . + + -or- + + is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. + + -or- + The could not be delivered to one or more of the recipients in , , or . The could not be delivered to one of the recipients in , , or . The could not be delivered to two or more of the recipients in , , or . @@ -1747,60 +1747,61 @@ The classes shown in the following table are used to construct email messages th Sends the specified message to an SMTP server for delivery as an asynchronous operation. The task object representing the asynchronous operation. - object will complete once the message has been sent. - + object will complete once the message has been sent. + ]]> is . - This has another send operation already in progress. - - -or- - - is . - - -or- - - There are no recipients specified in , , and properties. - - -or- - - property is set to and is . - - -or- - - property is set to and is equal to the empty string (""). - - -or- - + This has another send operation already in progress. + + -or- + + is . + + -or- + + There are no recipients specified in , , and properties. + + -or- + + property is set to and is . + + -or- + + property is set to and is equal to the empty string (""). + + -or- + property is set to and is zero, a negative number, or greater than 65,535. This object has been disposed. - The connection to the SMTP server failed. - - -or- - - Authentication failed. - - -or- - - The operation timed out. - - -or- - - is set to but the property is set to or . - - -or- - - is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. - - -or- - + The connection to the SMTP server failed. + + -or- + + Authentication failed. + + -or- + + The operation timed out. + + -or- + + is set to but the property is set to or . + + -or- + + is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. + + -or- + The could not be delivered to one or more of the recipients in , , or . The could not be delivered to one of the recipients in , , or . The could not be delivered to two or more of the recipients in , , or . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1848,63 +1849,63 @@ The classes shown in the following table are used to construct email messages th Sends the specified message to an SMTP server for delivery as an asynchronous operation. The message sender, recipients, subject, and message body are specified using objects. The task object representing the asynchronous operation. - object will complete once the message has been sent. - + object will complete once the message has been sent. + ]]> - is . - - -or- - + is . + + -or- + is . - is . - - -or- - + is . + + -or- + is . - This has another send operation already in progress. - - -or- - - is . - - -or- - - property is set to and is . - - -or- - - property is set to and is equal to the empty string (""). - - -or- - + This has another send operation already in progress. + + -or- + + is . + + -or- + + property is set to and is . + + -or- + + property is set to and is equal to the empty string (""). + + -or- + property is set to and is zero, a negative number, or greater than 65,535. This object has been disposed. - The connection to the SMTP server failed. - - -or- - - Authentication failed. - - -or- - - The operation timed out. - - -or- - - is set to but the property is set to or . - - -or- - - is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. - - -or- - + The connection to the SMTP server failed. + + -or- + + Authentication failed. + + -or- + + The operation timed out. + + -or- + + is set to but the property is set to or . + + -or- + + is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. + + -or- + The could not be delivered to one or more of the recipients in , , or . The could not be delivered to one of the recipients in , , or . The could not be delivered to two or more of the recipients in , , or . @@ -1946,62 +1947,63 @@ The classes shown in the following table are used to construct email messages th Sends the specified message to an SMTP server for delivery as an asynchronous operation, using the specified sender, recipients, subject, and body strings. The task object representing the asynchronous operation. - object will complete once the message has been sent. - + object will complete once the message has been sent. + ]]> - is . - - -or- - + is . + + -or- + is . - is . - - -or- - + is . + + -or- + is . - This has another send operation already in progress. - - -or- - - property is set to and is . - - -or- - - property is set to and is equal to the empty string (""). - - -or- - + This has another send operation already in progress. + + -or- + + property is set to and is . + + -or- + + property is set to and is equal to the empty string (""). + + -or- + property is set to and is zero, a negative number, or greater than 65,535. This object has been disposed. - The connection to the SMTP server failed. - - -or- - - Authentication failed. - - -or- - - The operation timed out. - - -or- - - is set to but the property is set to or . - - -or- - - is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. - - -or- - + The connection to the SMTP server failed. + + -or- + + Authentication failed. + + -or- + + The operation timed out. + + -or- + + is set to but the property is set to or . + + -or- + + is set to but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. + + -or- + The could not be delivered to one or more of the recipients in , , or . The could not be delivered to one of the recipients in , , or . The could not be delivered to two or more of the recipients in , , or . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2045,18 +2047,18 @@ The classes shown in the following table are used to construct email messages th Gets the network connection used to transmit the email message. A that connects to the property used for SMTP. - property are created using defaults specified in the application or machine configuration files and the class. - + property are created using defaults specified in the application or machine configuration files and the class. + ]]> - is or the empty string (""). - - -or- - + is or the empty string (""). + + -or- + is zero. connectionManagement Element (Network Settings) Managing Connections @@ -2108,13 +2110,13 @@ The classes shown in the following table are used to construct email messages th Gets or sets the Service Provider Name (SPN) to use for authentication when using extended protection. A that specifies the SPN to use for extended protection. The default value for this SPN is of the form "SMTPSVC/<host>" where <host> is the hostname of the SMTP mail server. - property is used with integrated Windows authentication when an application is using extended protection. The can then provide extended protection to ensure that credential challenge responses contain service specific information (a SPN) and, if necessary, channel specific information (a channel binding token or CBT). With this information in the credential exchanges, services are able to better protect against malicious use of credential challenge responses that might have been improperly obtained. - - The default value for this property can also be set in a machine or application configuration file. Any changes made to the property override the configuration file settings. - + property is used with integrated Windows authentication when an application is using extended protection. The can then provide extended protection to ensure that credential challenge responses contain service specific information (a SPN) and, if necessary, channel specific information (a channel binding token or CBT). With this information in the credential exchanges, services are able to better protect against malicious use of credential challenge responses that might have been improperly obtained. + + The default value for this property can also be set in a machine or application configuration file. Any changes made to the property override the configuration file settings. + ]]> @@ -2161,21 +2163,21 @@ The classes shown in the following table are used to construct email messages th Gets or sets a value that specifies the amount of time after which a synchronous call times out. An that specifies the time-out value in milliseconds. The default value is 100,000 (100 seconds). - method block until the operation completes. If you set the property to a positive value, and a operation cannot complete in the allotted time, the class throws an exception. - - To send a message and continue executing in the application thread, use the method. - - - -## Examples - The following code example demonstrates getting and setting the time-out value. - + method block until the operation completes. If you set the property to a positive value, and a operation cannot complete in the allotted time, the class throws an exception. + + To send a message and continue executing in the application thread, use the method. + + + +## Examples + The following code example demonstrates getting and setting the time-out value. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLMailSync/CPP/NclMailSync.cpp" id="Snippet3"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet3"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet3"::: + ]]> The value specified for a set operation was less than zero. @@ -2224,26 +2226,26 @@ The classes shown in the following table are used to construct email messages th if the default credentials are used; otherwise . The default value is . - object should, if requested by the server, authenticate using the default credentials of the currently logged on user. For client applications, this is the desired behavior in most scenarios. - - Credentials information can also be specified using the application and machine configuration files. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). - - If the property is set to `false,` then the value set in the property will be used for the credentials when connecting to the server. If the property is set to `false` and the property has not been set, then mail is sent to the server anonymously. - + object should, if requested by the server, authenticate using the default credentials of the currently logged on user. For client applications, this is the desired behavior in most scenarios. + + Credentials information can also be specified using the application and machine configuration files. For more information, see [<mailSettings> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/mailsettings-element-network-settings). + + If the property is set to `false,` then the value set in the property will be used for the credentials when connecting to the server. If the property is set to `false` and the property has not been set, then mail is sent to the server anonymously. + > [!CAUTION] -> If you provide credentials for basic authentication, they are sent to the server in clear text. This can present a security issue because your credentials can be seen, and then used by others. - - - -## Examples - The following code example demonstrates using this property. - +> If you provide credentials for basic authentication, they are sent to the server in clear text. This can present a security issue because your credentials can be seen, and then used by others. + + + +## Examples + The following code example demonstrates using this property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLMailSync/CPP/NclMailSync.cpp" id="Snippet2"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet2"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Mail/Attachment/Overview/mail.cs" id="Snippet2"::: + ]]> You cannot change the value of this property when an email is being sent. diff --git a/xml/System.Net.Quic/QuicConnection.xml b/xml/System.Net.Quic/QuicConnection.xml index 433c0d793c3..6324f632178 100644 --- a/xml/System.Net.Quic/QuicConnection.xml +++ b/xml/System.Net.Quic/QuicConnection.xml @@ -57,6 +57,7 @@ For QUIC prerequisites and supported operating systems, see [Platform dependenci Accepts an inbound . An asynchronous task that completes with the accepted . To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -94,6 +95,7 @@ If RFC 9000: Connection Termination + The cancellation token was canceled. This exception is stored into the returned task. @@ -120,6 +122,7 @@ If Creates a new and connects it to the peer. An asynchronous task that completes with the connected connection. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -235,6 +238,7 @@ If Creates an outbound unidirectional or bidirectional . An asynchronous task that completes with the opened . If the connection doesn't have any available stream capacity, that is, the peer limits the concurrent stream count, the operation pends until the peer increases the stream limit. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Quic/QuicListener.xml b/xml/System.Net.Quic/QuicListener.xml index f8f7b0b5083..1c7d0c22410 100644 --- a/xml/System.Net.Quic/QuicListener.xml +++ b/xml/System.Net.Quic/QuicListener.xml @@ -65,6 +65,7 @@ This method propagates exceptions from + The cancellation token was canceled. This exception is stored into the returned task. @@ -138,6 +139,7 @@ This method propagates exceptions from Creates a new and starts listening for new connections. An asynchronous task that completes with the started listener. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Quic/QuicStream.xml b/xml/System.Net.Quic/QuicStream.xml index 9611c87ac09..8696079608c 100644 --- a/xml/System.Net.Quic/QuicStream.xml +++ b/xml/System.Net.Quic/QuicStream.xml @@ -388,6 +388,7 @@ Equivalent to using To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -539,6 +540,7 @@ Equivalent to using To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -570,6 +572,7 @@ Equivalent to using To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -794,6 +797,7 @@ Equivalent to using To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -824,6 +828,7 @@ Equivalent to using To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -855,6 +860,7 @@ Equivalent to using To be added. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Security/NegotiateStream.xml b/xml/System.Net.Security/NegotiateStream.xml index 9fd72f8f1cc..892ea594e22 100644 --- a/xml/System.Net.Security/NegotiateStream.xml +++ b/xml/System.Net.Security/NegotiateStream.xml @@ -44,41 +44,41 @@ Provides a stream that uses the Negotiate security protocol to authenticate the client, and optionally the server, in client-server communication. - class for authentication and to help secure information transmitted between a client and a server. Using , you can do the following. - -- Send the client's credentials to the server for Impersonation or Delegation. - -- Request server authentication. - -- Encrypt and/or sign data before transmitting it. - - Authentication must be performed before transmitting information. Clients request authentication using the synchronous methods, which block until the authentication completes, or the asynchronous methods, which do not block while waiting for the authentication to complete. Servers request authentication using the synchronous or asynchronous methods. The client, and optionally the server, is authenticated using the Negotiate security protocol. The Kerberos protocol is used for authentication if both client and server support it; otherwise NTLM is used. The class performs the authentication using the Security Support Provider Interface (SSPI). - - When authentication succeeds, you must check the and properties to determine what security services will be used by the to help secure your data during transmission. Check the property to determine whether mutual authentication occurred. You can get information about the remote client or server using the property. - - If the authentication fails, you will receive an or a . In this case, you can retry the authentication with a different credential. - - You send data using the synchronous or asynchronous or methods. You receive data using the synchronous or asynchronous or methods. If security services such as encryption or signing are enabled, these are automatically applied to your data by the . - - The transmits data using a stream that you supply when creating the . When you supply this underlying stream, you have the option to specify whether closing the also closes the underlying stream. - - - -## Examples -The following example demonstrates the client side of a client-server connection that uses the . The client authenticates and sends a message to the server asynchronously. - + class for authentication and to help secure information transmitted between a client and a server. Using , you can do the following. + +- Send the client's credentials to the server for Impersonation or Delegation. + +- Request server authentication. + +- Encrypt and/or sign data before transmitting it. + + Authentication must be performed before transmitting information. Clients request authentication using the synchronous methods, which block until the authentication completes, or the asynchronous methods, which do not block while waiting for the authentication to complete. Servers request authentication using the synchronous or asynchronous methods. The client, and optionally the server, is authenticated using the Negotiate security protocol. The Kerberos protocol is used for authentication if both client and server support it; otherwise NTLM is used. The class performs the authentication using the Security Support Provider Interface (SSPI). + + When authentication succeeds, you must check the and properties to determine what security services will be used by the to help secure your data during transmission. Check the property to determine whether mutual authentication occurred. You can get information about the remote client or server using the property. + + If the authentication fails, you will receive an or a . In this case, you can retry the authentication with a different credential. + + You send data using the synchronous or asynchronous or methods. You receive data using the synchronous or asynchronous or methods. If security services such as encryption or signing are enabled, these are automatically applied to your data by the . + + The transmits data using a stream that you supply when creating the . When you supply this underlying stream, you have the option to specify whether closing the also closes the underlying stream. + + + +## Examples +The following example demonstrates the client side of a client-server connection that uses the . The client authenticates and sends a message to the server asynchronously. + [!code-cpp[NclNegoAsyncClient#0](~/snippets/cpp/VS_Snippets_Remoting/NclNegoasyncClient/CPP/NclNegoasyncClient.cpp#0)] -[!code-csharp[NclNegoAsyncClient#0](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#0)] -[!code-vb[NclNegoAsyncClient#0](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#0)] +[!code-csharp[NclNegoAsyncClient#0](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#0)] +[!code-vb[NclNegoAsyncClient#0](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#0)] + +The following code example demonstrates the server side of a client-server connection that uses the to authenticate the client and read a message sent by the client. -The following code example demonstrates the server side of a client-server connection that uses the to authenticate the client and read a message sent by the client. - [!code-cpp[NclNegoAsyncServer#0](~/snippets/cpp/VS_Snippets_Remoting/NclNegoAsyncServer/CPP/NclNegoAsyncServer.cpp#0)] -[!code-csharp[NclNegoAsyncServer#0](~/snippets/csharp/System.Net.Security/NegotiateStream/Overview/server.cs#0)] - +[!code-csharp[NclNegoAsyncServer#0](~/snippets/csharp/System.Net.Security/NegotiateStream/Overview/server.cs#0)] + ]]> Changes to NTLM authentication for HTTPWebRequest in Version 3.5 SP1 @@ -92,11 +92,11 @@ The following code example demonstrates the server side of a client-server conne Initializes a new instance of the class. - from closing the stream that you supply, use the constructor. - + from closing the stream that you supply, use the constructor. + ]]> @@ -147,14 +147,14 @@ The following code example demonstrates the server side of a client-server conne A object used by the for sending and receiving data. Initializes a new instance of the class using the specified . - @@ -204,27 +204,27 @@ The following code example demonstrates the server side of a client-server conne to indicate that closing this has no effect on ; to indicate that closing this also closes . Initializes a new instance of the class using the specified and stream closure behavior. - has no effect on the `innerStream` stream; you must explicitly close `innerStream` when you no longer need it. - - - -## Examples -The following example demonstrates calling this constructor. This code example is part of a larger example provided for the class. - + has no effect on the `innerStream` stream; you must explicitly close `innerStream` when you no longer need it. + + + +## Examples +The following example demonstrates calling this constructor. This code example is part of a larger example provided for the class. + [!code-cpp[NclNegoAsyncClient#1](~/snippets/cpp/VS_Snippets_Remoting/NclNegoasyncClient/CPP/NclNegoasyncClient.cpp#1)] -[!code-csharp[NclNegoAsyncClient#1](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#1)] -[!code-vb[NclNegoAsyncClient#1](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#1)] +[!code-csharp[NclNegoAsyncClient#1](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#1)] +[!code-vb[NclNegoAsyncClient#1](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#1)] ]]> - is . - + is . + -or- - + is equal to . @@ -279,24 +279,24 @@ The following example demonstrates calling this constructor. This code example i Called by clients to authenticate the client, and optionally the server, in a client-server connection. - . No Service Principal Name (SPN) is specified for the server. The impersonation level is , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + . No Service Principal Name (SPN) is specified for the server. The impersonation level is , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. @@ -350,22 +350,22 @@ The following example demonstrates calling this constructor. This code example i The Service Principal Name (SPN) that uniquely identifies the server to authenticate. Called by clients to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified client credential. - , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - + , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + ]]> The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. is . @@ -424,29 +424,29 @@ The following example demonstrates calling this constructor. This code example i The Service Principal Name (SPN) that uniquely identifies the server to authenticate. Called by clients to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified client credential and the channel binding. - , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. - - The used for extended protection that is passed to this method in the `binding` parameter would be retrieved by an application from property on the associated . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - + , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. + + The used for extended protection that is passed to this method in the `binding` parameter would be retrieved by an application from property on the associated . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + ]]> - is . - + is . + -or- - + is . The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. This object has been closed. @@ -507,13 +507,13 @@ The following example demonstrates calling this constructor. This code example i One of the values, indicating how the server can use the client's credentials to access resources. Called by clients to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified credentials and authentication options. - value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> @@ -523,10 +523,10 @@ The following example demonstrates calling this constructor. This code example i The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. @@ -583,31 +583,31 @@ The following example demonstrates calling this constructor. This code example i One of the values, indicating how the server can use the client's credentials to access resources. Called by clients to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified credential, authentication options, and channel binding. - value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . - - The used for extended protection that is passed to this method in the `binding` parameter would be retrieved by an application from property on the associated . - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . + + The used for extended protection that is passed to this method in the `binding` parameter would be retrieved by an application from property on the associated . + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> - is . - + is . + -or- - + is . is not a valid value. The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. This object has been closed. @@ -660,15 +660,15 @@ The following example demonstrates calling this constructor. This code example i Called by clients to authenticate the client, and optionally the server, in a client-server connection as an asynchronous operation. The task object representing the asynchronous operation. - . No Service Principal Name (SPN) is specified for the server. The impersonation level is , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + . No Service Principal Name (SPN) is specified for the server. The impersonation level is , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -676,10 +676,10 @@ The following example demonstrates calling this constructor. This code example i The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. @@ -724,13 +724,13 @@ The following example demonstrates calling this constructor. This code example i Called by clients to authenticate the client, and optionally the server, in a client-server connection as an asynchronous operation. The authentication process uses the specified client credential. The task object representing the asynchronous operation. - , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - + , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -738,10 +738,10 @@ The following example demonstrates calling this constructor. This code example i The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. is . @@ -791,31 +791,31 @@ The following example demonstrates calling this constructor. This code example i Called by clients to authenticate the client, and optionally the server, in a client-server connection as an asynchronous operation. The authentication process uses the specified client credential and the channel binding. The task object representing the asynchronous operation. - , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. - - The used for extended protection that is passed to this method in the `binding` parameter would be retrieved by an application from property on the associated . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - + , the security level is , and mutual authentication is requested. The class will construct the SPN used for mutual authentication. + + The used for extended protection that is passed to this method in the `binding` parameter would be retrieved by an application from property on the associated . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - is . - + is . + -or- - + is . The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. This object has been closed. @@ -867,13 +867,13 @@ The following example demonstrates calling this constructor. This code example i Called by clients to authenticate the client, and optionally the server, in a client-server connection as an asynchronous operation. The authentication process uses the specified credentials and authentication options. The task object representing the asynchronous operation. - value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -885,10 +885,10 @@ The following example demonstrates calling this constructor. This code example i The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. @@ -940,33 +940,33 @@ The following example demonstrates calling this constructor. This code example i Called by clients to authenticate the client, and optionally the server, in a client-server connection as an asynchronous operation. The authentication process uses the specified credential, authentication options, and channel binding. The task object representing the asynchronous operation. - value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . - - The used for extended protection that is passed to this method in the `binding` parameter would be retrieved by an application from property on the associated . - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . + + The used for extended protection that is passed to this method in the `binding` parameter would be retrieved by an application from property on the associated . + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> - is . - + is . + -or- - + is . is not a valid value. The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. This object has been closed. @@ -982,11 +982,11 @@ The following example demonstrates calling this constructor. This code example i Handles the server side of an authentication for a client-server connection. - method. - + method. + ]]> @@ -1032,17 +1032,17 @@ The following example demonstrates calling this constructor. This code example i Called by servers to authenticate the client, and optionally the server, in a client-server connection. - . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> The authentication failed. You can use this object to retry the authentication. @@ -1096,19 +1096,19 @@ The following example demonstrates calling this constructor. This code example i The that is used for extended protection. Called by servers to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified extended protection policy. - . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . - - If the `policy` parameter is `null`, then an extended protection policy is used that has set to . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . + + If the `policy` parameter is `null`, then an extended protection policy is used that has set to . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> The and on the extended protection policy passed in the parameter are both . @@ -1173,15 +1173,15 @@ The following example demonstrates calling this constructor. This code example i One of the values, indicating how the server can use the client's credentials to access resources. Called by servers to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified server credentials and authentication options. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> @@ -1191,10 +1191,10 @@ The following example demonstrates calling this constructor. This code example i The authentication failed. You can use this object to try to r-authenticate. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the client. You cannot use the stream to retry authentication as the server. Windows 95 and Windows 98 are not supported. @@ -1250,17 +1250,17 @@ The following example demonstrates calling this constructor. This code example i One of the values, indicating how the server can use the client's credentials to access resources. Called by servers to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified server credentials, authentication options, and extended protection policy. - set to . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + set to . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> The and on the extended protection policy passed in the parameter are both . @@ -1270,10 +1270,10 @@ The following example demonstrates calling this constructor. This code example i must be , , or , The authentication failed. You can use this object to try to r-authenticate. The authentication failed. You can use this object to retry the authentication. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the client. You cannot use the stream to retry authentication as the server. This object has been closed. The parameter was set to on a platform that does not support extended protection. @@ -1328,15 +1328,15 @@ The following example demonstrates calling this constructor. This code example i Called by servers to authenticate the client, and optionally the server, in a client-server connection as an asynchronous operation. The task object representing the asynchronous operation. - . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1387,17 +1387,17 @@ The following example demonstrates calling this constructor. This code example i Called by servers to authenticate the client, and optionally the server, in a client-server connection as an asynchronous operation. The authentication process uses the specified extended protection policy. The task object representing the asynchronous operation. - . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . - - If the `policy` parameter is `null`, then an extended protection policy is used that has set to . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . + + If the `policy` parameter is `null`, then an extended protection policy is used that has set to . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1455,13 +1455,13 @@ The following example demonstrates calling this constructor. This code example i Called by servers to authenticate the client, and optionally the server, in a client-server connection as an asynchronous operation. The authentication process uses the specified server credentials and authentication options. The task object representing the asynchronous operation. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1473,10 +1473,10 @@ The following example demonstrates calling this constructor. This code example i The authentication failed. You can use this object to try to r-authenticate. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the client. You cannot use the stream to retry authentication as the server. Windows 95 and Windows 98 are not supported. @@ -1527,15 +1527,15 @@ The following example demonstrates calling this constructor. This code example i Called by servers to authenticate the client, and optionally the server, in a client-server connection as an asynchronous operation. The authentication process uses the specified server credentials, authentication options, and extended protection policy. The task object representing the asynchronous operation. - set to . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + set to . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1547,10 +1547,10 @@ The following example demonstrates calling this constructor. This code example i must be , , or , The authentication failed. You can use this object to try to r-authenticate. The authentication failed. You can use this object to retry the authentication. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the client. You cannot use the stream to retry authentication as the server. This object has been closed. The parameter was set to on a platform that does not support extended protection. @@ -1568,11 +1568,11 @@ The following example demonstrates calling this constructor. This code example i Begins an asynchronous operation to authenticate the client side of a client-server connection. - methods. - + methods. + ]]> @@ -1625,35 +1625,35 @@ The following example demonstrates calling this constructor. This code example i Called by clients to begin an asynchronous operation to authenticate the client, and optionally the server, in a client-server connection. This method does not block. An object indicating the status of the asynchronous operation. - . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . The class will construct the SPN used for mutual authentication. - - This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - - - -## Examples -The following example demonstrates calling this method to begin an asynchronous authentication for the client. - + . No Service Principal Name (SPN) is specified for the server. The impersonation level is , and the security level is . The class will construct the SPN used for mutual authentication. + + This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + + + +## Examples +The following example demonstrates calling this method to begin an asynchronous authentication for the client. + [!code-cpp[NclNegoAsyncClient#2](~/snippets/cpp/VS_Snippets_Remoting/NclNegoasyncClient/CPP/NclNegoasyncClient.cpp#2)] -[!code-csharp[NclNegoAsyncClient#2](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#2)] -[!code-vb[NclNegoAsyncClient#2](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#2)] +[!code-csharp[NclNegoAsyncClient#2](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#2)] +[!code-vb[NclNegoAsyncClient#2](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#2)] ]]> The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. @@ -1713,30 +1713,30 @@ The following example demonstrates calling this method to begin an asynchronous Called by clients to begin an asynchronous operation to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified credentials. This method does not block. An object indicating the status of the asynchronous operation. - method overloads. - - The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + method overloads. + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> - is . - + is . + -or- - + is . The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. @@ -1798,29 +1798,29 @@ The following example demonstrates calling this method to begin an asynchronous Called by clients to begin an asynchronous operation to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified credentials and channel binding. This method does not block. An object indicating the status of the asynchronous operation. - method overloads. - - The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + method overloads. + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> - is . - + is . + -or- - + is . The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. This object has been closed. @@ -1887,32 +1887,32 @@ The following example demonstrates calling this method to begin an asynchronous Called by clients to begin an asynchronous operation to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified credentials and authentication options. This method does not block. An object indicating the status of the asynchronous operation. - value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . - - This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . + + This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> - is . - + is . + -or- - + is . The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. @@ -1974,31 +1974,31 @@ The following example demonstrates calling this method to begin an asynchronous Called by clients to begin an asynchronous operation to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified credentials, authentication options, and channel binding. This method does not block. An object indicating the status of the asynchronous operation. - value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . - - This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + value. Successful authentication does not guarantee that the requested has been granted. You must check the and properties to determine what security services are used by the . + + This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> - is . - + is . + -or- - + is . The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the server. You cannot use the stream to retry authentication as the client. This object has been closed. @@ -2014,11 +2014,11 @@ The following example demonstrates calling this method to begin an asynchronous Begins an asynchronous operation to handle the server side of authenticating a client-server connection. - method. - + method. + ]]> @@ -2071,17 +2071,17 @@ The following example demonstrates calling this method to begin an asynchronous Called by servers to begin an asynchronous operation to authenticate the client, and optionally the server, in a client-server connection. This method does not block. An object indicating the status of the asynchronous operation. - . No Service Principal Name (SPN) is specified for the server. The impersonation level is , the security level is . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - To block until the operation completes, use one of the method overloads. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + . No Service Principal Name (SPN) is specified for the server. The impersonation level is , the security level is . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + To block until the operation completes, use one of the method overloads. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> The authentication failed. You can use this object to retry the authentication. @@ -2140,25 +2140,25 @@ The following example demonstrates calling this method to begin an asynchronous Called by servers to begin an asynchronous operation to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified extended protection policy. This method does not block. An object indicating the status of the asynchronous operation. - . No Service Principal Name (SPN) is specified for the server. The impersonation level is , the security level is . - - If the `policy` parameter is `null`, then an extended protection policy is used that has set to . - - When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - To block until the operation completes, use one of the method overloads. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - - ]]> - - The and on the extended protection policy passed in the parameter are both . - The authentication failed. You can use this object to retry the authentication. - The authentication failed. You can use this object to retry the authentication. - This object has been closed. + . No Service Principal Name (SPN) is specified for the server. The impersonation level is , the security level is . + + If the `policy` parameter is `null`, then an extended protection policy is used that has set to . + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + To block until the operation completes, use one of the method overloads. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + + ]]> + + The and on the extended protection policy passed in the parameter are both . + The authentication failed. You can use this object to retry the authentication. + The authentication failed. You can use this object to retry the authentication. + This object has been closed. The parameter was set to on a platform that does not support extended protection. Integrated Windows Authentication with Extended Protection @@ -2223,17 +2223,17 @@ The following example demonstrates calling this method to begin an asynchronous Called by servers to begin an asynchronous operation to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified server credentials and authentication options. This method does not block. An object indicating the status of the asynchronous operation. - value. Successful authentication does not guarantee that, the requested has been granted. You must check the and properties to determine what security services are used by the . - - This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + value. Successful authentication does not guarantee that, the requested has been granted. You must check the and properties to determine what security services are used by the . + + This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> @@ -2243,10 +2243,10 @@ The following example demonstrates calling this method to begin an asynchronous The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. This object has been closed. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the client. You cannot use the stream to retry authentication as the server. Windows 95 and Windows 98 are not supported. @@ -2307,19 +2307,19 @@ The following example demonstrates calling this method to begin an asynchronous Called by servers to begin an asynchronous operation to authenticate the client, and optionally the server, in a client-server connection. The authentication process uses the specified server credentials, authentication options, and extended protection policy. This method does not block. An object indicating the status of the asynchronous operation. - value. Successful authentication does not guarantee that, the requested has been granted. You must check the and properties to determine what security services are used by the . - - If the `policy` parameter is `null`, then an extended protection policy is used that has set to . - - This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - + value. Successful authentication does not guarantee that, the requested has been granted. You must check the and properties to determine what security services are used by the . + + If the `policy` parameter is `null`, then an extended protection policy is used that has set to . + + This method is asynchronous and does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + ]]> The and on the extended protection policy passed in the parameter are both . @@ -2329,10 +2329,10 @@ The following example demonstrates calling this method to begin an asynchronous must be , , or , The authentication failed. You can use this object to retry the authentication. The authentication failed. You can use this object to retry the authentication. - Authentication has already occurred. - + Authentication has already occurred. + -or- - + This stream was used previously to attempt authentication as the client. You cannot use the stream to retry authentication as the server. This object has been closed. The parameter was set to on a platform that does not support extended protection. @@ -2395,45 +2395,45 @@ The following example demonstrates calling this method to begin an asynchronous Begins an asynchronous read operation that reads data from the stream and stores it in the specified array. An object indicating the status of the asynchronous operation. - method. - - The asynchronous read operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - The class does not support multiple simultaneous read operations. If you attempt to start a read operation while another read operation is already executing on the same stream, a exception will be thrown. - - You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. - - - -## Examples - The following code example demonstrates starting an asynchronous read operation. This code example is part of a larger example provided for the class. - + method. + + The asynchronous read operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + The class does not support multiple simultaneous read operations. If you attempt to start a read operation while another read operation is already executing on the same stream, a exception will be thrown. + + You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. + + + +## Examples + The following code example demonstrates starting an asynchronous read operation. This code example is part of a larger example provided for the class. + [!code-cpp[NclNegoAsyncServer#1](~/snippets/cpp/VS_Snippets_Remoting/NclNegoAsyncServer/CPP/NclNegoAsyncServer.cpp#1)] - [!code-csharp[NclNegoAsyncServer#1](~/snippets/csharp/System.Net.Security/NegotiateStream/Overview/server.cs#1)] - + [!code-csharp[NclNegoAsyncServer#1](~/snippets/csharp/System.Net.Security/NegotiateStream/Overview/server.cs#1)] + ]]> is . - is less than 0. - + is less than 0. + -or- - - is greater than the length of . - + + is greater than the length of . + -or- - + plus is greater than the length of . - The read operation failed. - + The read operation failed. + -or- - + Encryption is in use, but the data could not be decrypted. There is already a read operation in progress. This object has been closed. @@ -2494,52 +2494,52 @@ The following example demonstrates calling this method to begin an asynchronous Begins an asynchronous write operation that writes s from the specified buffer to the stream. An object indicating the status of the asynchronous operation. - method. - - The asynchronous read operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - The class does not support multiple simultaneous write operations. If you attempt to start a write operation while another write operation is already executing on the same stream, a exception will be thrown. - - You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. - - - -## Examples -The following example demonstrates beginning an asynchronous write operation. - + method. + + The asynchronous read operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + The class does not support multiple simultaneous write operations. If you attempt to start a write operation while another write operation is already executing on the same stream, a exception will be thrown. + + You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. + + + +## Examples +The following example demonstrates beginning an asynchronous write operation. + [!code-cpp[NclNegoAsyncClient#3](~/snippets/cpp/VS_Snippets_Remoting/NclNegoasyncClient/CPP/NclNegoasyncClient.cpp#3)] -[!code-csharp[NclNegoAsyncClient#3](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#3)] -[!code-vb[NclNegoAsyncClient#3](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#3)] +[!code-csharp[NclNegoAsyncClient#3](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#3)] +[!code-vb[NclNegoAsyncClient#3](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#3)] + +The following method is called when the operation completes. -The following method is called when the operation completes. - [!code-cpp[NclNegoAsyncClient#4](~/snippets/cpp/VS_Snippets_Remoting/NclNegoasyncClient/CPP/NclNegoasyncClient.cpp#4)] -[!code-csharp[NclNegoAsyncClient#4](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#4)] -[!code-vb[NclNegoAsyncClient#4](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#4)] +[!code-csharp[NclNegoAsyncClient#4](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#4)] +[!code-vb[NclNegoAsyncClient#4](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#4)] ]]> is . - . - + . + -or- - - is greater than the length of . - + + is greater than the length of . + -or- - + plus count is greater than the length of . - The write operation failed. - + The write operation failed. + -or- - + Encryption is in use, but the data could not be encrypted. There is already a write operation in progress. This object has been closed. @@ -2583,19 +2583,19 @@ The following method is called when the operation completes. if authentication has occurred and the underlying stream is readable; otherwise, . - property on the underlying stream. The underlying stream is specified when you create an instance of the class. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + property on the underlying stream. The underlying stream is specified when you create an instance of the class. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#2](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#2)] - [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] - + [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] + ]]> @@ -2636,19 +2636,19 @@ The following method is called when the operation completes. Gets a value that indicates whether the underlying stream is seekable. This property always returns . - object or its underlying stream. The underlying stream is specified when you create an instance of the class. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + object or its underlying stream. The underlying stream is specified when you create an instance of the class. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#2](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#2)] - [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] - + [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] + ]]> @@ -2697,19 +2697,19 @@ The following method is called when the operation completes. if the underlying stream supports time-outs; otherwise, . - property on the underlying stream. The underlying stream is specified when you create an instance of the class. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + property on the underlying stream. The underlying stream is specified when you create an instance of the class. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#2](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#2)] - [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] - + [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] + ]]> @@ -2751,19 +2751,19 @@ The following method is called when the operation completes. if authentication has occurred and the underlying stream is writable; otherwise, . - property on the underlying stream. The underlying stream is specified when you create an instance of the class. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + property on the underlying stream. The underlying stream is specified when you create an instance of the class. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#2](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#2)] - [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] - + [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] + ]]> @@ -2813,19 +2813,19 @@ The following method is called when the operation completes. to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. - - When the `disposing` parameter is true, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - + + When the `disposing` parameter is true, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Overriding the Finalize Method](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ddae83kx(v=vs.100)). @@ -2858,15 +2858,15 @@ The following method is called when the operation completes. Asynchronously releases the unmanaged and managed resources used by the . A task that represents the asynchronous dispose operation. - is `false`; otherwise, the inner stream is just flushed. - + Calling `DisposeAsync` allows the resources used by the to be reallocated for other purposes. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). - + ]]> @@ -2915,15 +2915,15 @@ The following method is called when the operation completes. An instance returned by a call to . Ends a pending asynchronous client authentication operation that was started with a call to . - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - - To perform this operation synchronously, use one of the method. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + + To perform this operation synchronously, use one of the method. + ]]> @@ -2979,17 +2979,17 @@ The following method is called when the operation completes. An instance returned by a call to . Ends a pending asynchronous client authentication operation that was started with a call to . - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. - - To perform this operation synchronously, use the method. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive an or an . In this case, you can retry the authentication with a different credential. + + To perform this operation synchronously, use the method. + ]]> @@ -3046,23 +3046,23 @@ The following method is called when the operation completes. Ends an asynchronous read operation that was started with a call to . A value that specifies the number of bytes read from the underlying stream. - method. - - You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. - - - -## Examples - The following code example demonstrates ending an asynchronous read operation. For an example that demonstrates starting the operation, see . - + method. + + You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. + + + +## Examples + The following code example demonstrates ending an asynchronous read operation. For an example that demonstrates starting the operation, see . + [!code-cpp[NclNegoAsyncServer#3](~/snippets/cpp/VS_Snippets_Remoting/NclNegoAsyncServer/CPP/NclNegoAsyncServer.cpp#3)] - [!code-csharp[NclNegoAsyncServer#3](~/snippets/csharp/System.Net.Security/NegotiateStream/Overview/server.cs#3)] - + [!code-csharp[NclNegoAsyncServer#3](~/snippets/csharp/System.Net.Security/NegotiateStream/Overview/server.cs#3)] + ]]> @@ -3120,23 +3120,23 @@ Authentication has not occurred. An instance returned by a call to . Ends an asynchronous write operation that was started with a call to . - , , , , , or methods. - - To perform this operation synchronously, use the method. - - - -## Examples -The following example demonstrates a method that is called to complete the asynchronous write operation. For an example that demonstrates starting the operation, see . - + , , , , , or methods. + + To perform this operation synchronously, use the method. + + + +## Examples +The following example demonstrates a method that is called to complete the asynchronous write operation. For an example that demonstrates starting the operation, see . + [!code-cpp[NclNegoAsyncClient#4](~/snippets/cpp/VS_Snippets_Remoting/NclNegoasyncClient/CPP/NclNegoasyncClient.cpp#4)] -[!code-csharp[NclNegoAsyncClient#4](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#4)] -[!code-vb[NclNegoAsyncClient#4](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#4)] +[!code-csharp[NclNegoAsyncClient#4](~/snippets/csharp/System.Net.Security/AuthenticatedStream/Overview/client.cs#4)] +[!code-vb[NclNegoAsyncClient#4](~/snippets/visualbasic/VS_Snippets_Remoting/NclNegoasyncClient/VB/client.vb#4)] ]]> @@ -3193,19 +3193,19 @@ Authentication has not occurred. Causes any buffered data to be written to the underlying device. - on the underlying stream. - - - -## Examples - The following code example demonstrates flushing the stream. - + on the underlying stream. + + + +## Examples + The following code example demonstrates flushing the stream. + [!code-cpp[NclNegoSyncClient#4](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#4)] - [!code-csharp[NclNegoSyncClient#4](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#4)] - + [!code-csharp[NclNegoSyncClient#4](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#4)] + ]]> @@ -3242,15 +3242,16 @@ Authentication has not occurred. Asynchronously writes any buffered data to the underlying device. A task that represents the asynchronous flush operation. - on the underlying stream. - + on the underlying stream. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -3295,19 +3296,19 @@ Authentication has not occurred. Gets a value that indicates how the server can use the client's credentials. One of the values. - or methods. If you authenticate without specifying a , is used. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + or methods. If you authenticate without specifying a , is used. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#1](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#1)] - [!code-csharp[NclNegoSyncClient#1](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#1)] - + [!code-csharp[NclNegoSyncClient#1](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#1)] + ]]> Authentication failed or has not occurred. @@ -3356,19 +3357,19 @@ Authentication has not occurred. if successful authentication occurred; otherwise, . - or methods. Servers authenticate by calling the or methods. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + or methods. Servers authenticate by calling the or methods. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#1](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#1)] - [!code-csharp[NclNegoSyncClient#1](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#1)] - + [!code-csharp[NclNegoSyncClient#1](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#1)] + ]]> @@ -3416,19 +3417,19 @@ Authentication has not occurred. if data is encrypted before being transmitted over the network and decrypted when it reaches the remote endpoint; otherwise, . - @@ -3477,21 +3478,21 @@ Authentication has not occurred. if the server has been authenticated; otherwise, . - @@ -3539,21 +3540,21 @@ Authentication has not occurred. if the local endpoint was successfully authenticated as the server side of the authenticated connection; otherwise, . - or methods. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + or methods. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#1](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#1)] - [!code-csharp[NclNegoSyncClient#1](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#1)] - + [!code-csharp[NclNegoSyncClient#1](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#1)] + ]]> @@ -3601,19 +3602,19 @@ Authentication has not occurred. if the data is signed before being transmitted; otherwise, . - @@ -3654,19 +3655,19 @@ Authentication has not occurred. Gets the length of the underlying stream. A that specifies the length of the underlying stream. - property on the underlying stream. If the underlying stream is not seekable, this property will typically throw an exception. The run-time type of the underlying stream determines the run-time type of the exception that is thrown. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + property on the underlying stream. If the underlying stream is not seekable, this property will typically throw an exception. The run-time type of the underlying stream determines the run-time type of the exception that is thrown. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#2](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#2)] - [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] - + [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] + ]]> Getting the value of this property is not supported when the underlying stream is a . @@ -3708,17 +3709,17 @@ Authentication has not occurred. Gets or sets the current position in the underlying stream. A that specifies the current position in the underlying stream. - property on the underlying stream. If the underlying stream is not seekable, this property will typically throw an exception. The run-time type of the underlying stream determines the run-time type of the exception that is thrown. - + property on the underlying stream. If the underlying stream is not seekable, this property will typically throw an exception. The run-time type of the underlying stream determines the run-time type of the exception that is thrown. + ]]> - Setting this property is not supported. - + Setting this property is not supported. + -or- - + Getting the value of this property is not supported when the underlying stream is a . @@ -3772,23 +3773,23 @@ Authentication has not occurred. Reads data from this stream and stores it in the specified array. An value that specifies the number of bytes read from the underlying stream. When there is no more data to be read, returns 0. - , , , , , or methods. - - To perform this operation asynchronously, use the method. - - - -## Examples - The following code example demonstrates reading from a . - + , , , , , or methods. + + To perform this operation asynchronously, use the method. + + + +## Examples + The following code example demonstrates reading from a . + [!code-cpp[NclNegoSyncServer#1](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncServer/CPP/NclNegoSyncServer.cpp#1)] - [!code-csharp[NclNegoSyncServer#1](~/snippets/csharp/System.Net.Security/NegotiateStream/Read/server.cs#1)] - + [!code-csharp[NclNegoSyncServer#1](~/snippets/csharp/System.Net.Security/NegotiateStream/Read/server.cs#1)] + ]]> The read operation failed. @@ -3825,17 +3826,18 @@ Authentication has not occurred. Reads data asynchronously from the and stores it in a byte memory range as an asynchronous operation. A that represents the asynchronous read operation. The value of its property contains the total number of bytes read into . - , , , , , or methods. - + ]]> The read operation failed. Authentication has not occurred. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3872,13 +3874,13 @@ This method reads asynchronously as much data as is available into `buffer` and Reads data asynchronously from this stream and stores it in the specified array. An value that specifies the number of bytes read from the underlying stream. When there is no more data to be read, returns 0. - , , , , , or methods. - + , , , , , or methods. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -3886,6 +3888,7 @@ This method reads asynchronously as much data as is available into `buffer` and The read operation failed. Authentication has not occurred. A operation is already in progress. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3924,21 +3927,21 @@ This method reads asynchronously as much data as is available into `buffer` and Gets or sets the amount of time a read operation blocks waiting for data. A that specifies the amount of time that will elapse before a read operation fails. - property on the underlying stream. When you set this property, the value on the underlying stream is set to the specified value. - - If the underlying stream is a , is in milliseconds and is set to by default so that read operations do not time out. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + property on the underlying stream. When you set this property, the value on the underlying stream is set to the specified value. + + If the underlying stream is a , is in milliseconds and is set to by default so that read operations do not time out. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#2](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#2)] - [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] - + [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] + ]]> @@ -3985,19 +3988,19 @@ This method reads asynchronously as much data as is available into `buffer` and Gets information about the identity of the remote party sharing this authenticated stream. An object that describes the identity of the remote endpoint. - containing the Service Principal Name (SPN) of the server and the authentication protocol used. When accessed by the server, this property returns a that describes the client. If the is not available, client information is returned to the server in a . - - - -## Examples - The following code example demonstrates displaying the value of this property. - + containing the Service Principal Name (SPN) of the server and the authentication protocol used. When accessed by the server, this property returns a that describes the client. If the is not available, client information is returned to the server in a . + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoAsyncServer#2](~/snippets/cpp/VS_Snippets_Remoting/NclNegoAsyncServer/CPP/NclNegoAsyncServer.cpp#2)] - [!code-csharp[NclNegoAsyncServer#2](~/snippets/csharp/System.Net.Security/NegotiateStream/Overview/server.cs#2)] - + [!code-csharp[NclNegoAsyncServer#2](~/snippets/csharp/System.Net.Security/NegotiateStream/Overview/server.cs#2)] + ]]> Authentication failed or has not occurred. @@ -4051,11 +4054,11 @@ This method reads asynchronously as much data as is available into `buffer` and Throws . Always throws a . - . - + . + ]]> Seeking is not supported on . @@ -4157,43 +4160,43 @@ This method reads asynchronously as much data as is available into `buffer` and A containing the number of bytes to read from . Write the specified number of s to the underlying stream using the specified buffer and offset. - on the underlying stream. - - This method blocks while the write operation completes. To prevent blocking while the operation completes, use the method. - - You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. - - The class does not support multiple simultaneous write operations. If you attempt to start a write operation while another write operation is already executing on the same stream, a exception will be thrown. - - - -## Examples - The following code example demonstrates writing to a . - + on the underlying stream. + + This method blocks while the write operation completes. To prevent blocking while the operation completes, use the method. + + You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. + + The class does not support multiple simultaneous write operations. If you attempt to start a write operation while another write operation is already executing on the same stream, a exception will be thrown. + + + +## Examples + The following code example demonstrates writing to a . + [!code-cpp[NclNegoSyncClient#4](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#4)] - [!code-csharp[NclNegoSyncClient#4](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#4)] - + [!code-csharp[NclNegoSyncClient#4](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#4)] + ]]> is . - . - + . + -or- - - is greater than the length of . - + + is greater than the length of . + -or- - + plus count is greater than the length of . - The write operation failed. - + The write operation failed. + -or- - + Encryption is in use, but the data could not be encrypted. There is already a write operation in progress. This object has been closed. @@ -4229,17 +4232,18 @@ This method reads asynchronously as much data as is available into `buffer` and Write asynchronously the specified number of s to the underlying stream. A that represents the asynchronous read operation. - on the underlying stream. - - You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. - + on the underlying stream. + + You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. + ]]> This object has been closed. Authentication has not occurred. + The cancellation token was canceled. This exception is stored into the returned task. @@ -4277,33 +4281,34 @@ This method reads asynchronously as much data as is available into `buffer` and A that represents the asynchronous read operation. on the underlying stream. - - You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. - + + You cannot call this method until you have successfully authenticated. To authenticate, call one of the , , , , , or methods. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. is . - . - + . + -or- - + is greater than the length of . - + -or- - + plus count is greater than the length of . The write operation failed. - + -or- - + Encryption is in use, but the data could not be encrypted. This object has been closed. Authentication has not occurred. @@ -4344,21 +4349,21 @@ This method reads asynchronously as much data as is available into `buffer` and Gets or sets the amount of time a write operation blocks waiting for data. A that specifies the amount of time that will elapse before a write operation fails. - property on the underlying stream. For set operations, the specified value sets the value on the underlying stream. - - If the underlying stream is a , is in milliseconds and is set to by default so that write operations do not time out. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + property on the underlying stream. For set operations, the specified value sets the value on the underlying stream. + + If the underlying stream is a , is in milliseconds and is set to by default so that write operations do not time out. + + + +## Examples + The following code example demonstrates displaying the value of this property. + [!code-cpp[NclNegoSyncClient#2](~/snippets/cpp/VS_Snippets_Remoting/NclNegoSyncClient/CPP/NclNegoSyncClient.cpp#2)] - [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] - + [!code-csharp[NclNegoSyncClient#2](~/snippets/csharp/System.Net.Security/NegotiateStream/.ctor/client.cs#2)] + ]]> diff --git a/xml/System.Net.Security/SslStream.xml b/xml/System.Net.Security/SslStream.xml index ca995cbc4ff..54d823ba02a 100644 --- a/xml/System.Net.Security/SslStream.xml +++ b/xml/System.Net.Security/SslStream.xml @@ -44,61 +44,61 @@ Provides a stream used for client-server communication that uses the Secure Socket Layer (SSL) security protocol to authenticate the server and optionally the client. - . An SSL connection, such as that provided by , should be used when communicating sensitive information between a client and a server. Using an helps to prevent anyone from reading and tampering with information while it is in transit on the network. - - An instance transmits data using a stream that you supply when creating the . When you supply this underlying stream, you have the option to specify whether closing the also closes the underlying stream. Typically, the class is used with the and classes. The method provides a suitable for use with the class. - - After creating an , the server and optionally, the client must be authenticated. The server must provide an X509 certificate that establishes proof of its identity and can request that the client also do so. Authentication must be performed before transmitting information using an . Clients initiate authentication using the synchronous methods, which block until the authentication completes, or the asynchronous methods, which do not block waiting for the authentication to complete. Servers initiate authentication using the synchronous or asynchronous methods. Both client and server must initiate the authentication. - - The authentication is handled by the Security Support Provider (SSPI) channel provider. The client is given an opportunity to control validation of the server's certificate by specifying a delegate when creating an . The server can also control validation by supplying a delegate. The method referenced by the delegate includes the remote party's certificate and any errors SSPI encountered while validating the certificate. Note that if the server specifies a delegate, the delegate's method is invoked regardless of whether the server requested client authentication. If the server did not request client authentication, the server's delegate method receives a null certificate and an empty array of certificate errors. - - If the server requires client authentication, the client must specify one or more certificates for authentication. If the client has more than one certificate, the client can provide a delegate to select the correct certificate for the server. The client's certificates must be located in the current user's "My" certificate store. Client authentication via certificates is not supported for the (SSL version 2) protocol. - - If the authentication fails, you receive a , and the is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - - When the authentication process, also known as the SSL handshake, succeeds, the identity of the server (and optionally, the client) is established and the can be used by the client and server to exchange messages. Before sending or receiving information, the client and server should check the security services and levels provided by the to determine whether the protocol, algorithms, and strengths selected meet their requirements for integrity and confidentiality. If the current settings are not sufficient, the stream should be closed. You can check the security services provided by the using the and properties. The following table shows the elements that report the cryptographic settings used for authentication, encryption and data signing. - -|Element|Members| -|-------------|-------------| -|The security protocol used to authenticate the server and, optionally, the client.|The property and the associated enumeration.| -|The key exchange algorithm.|The property and the associated enumeration.| -|The message integrity algorithm.|The property and the associated enumeration.| -|The message confidentiality algorithm.|The property and the associated enumeration.| -|The strengths of the selected algorithms.|The , , and properties.| - - After a successful authentication, you can send data using the synchronous or asynchronous methods. You can receive data using the synchronous or asynchronous methods. - - If you specified to the that the underlying stream should be left open, you are responsible for closing that stream when you are done using it. - + . An SSL connection, such as that provided by , should be used when communicating sensitive information between a client and a server. Using an helps to prevent anyone from reading and tampering with information while it is in transit on the network. + + An instance transmits data using a stream that you supply when creating the . When you supply this underlying stream, you have the option to specify whether closing the also closes the underlying stream. Typically, the class is used with the and classes. The method provides a suitable for use with the class. + + After creating an , the server and optionally, the client must be authenticated. The server must provide an X509 certificate that establishes proof of its identity and can request that the client also do so. Authentication must be performed before transmitting information using an . Clients initiate authentication using the synchronous methods, which block until the authentication completes, or the asynchronous methods, which do not block waiting for the authentication to complete. Servers initiate authentication using the synchronous or asynchronous methods. Both client and server must initiate the authentication. + + The authentication is handled by the Security Support Provider (SSPI) channel provider. The client is given an opportunity to control validation of the server's certificate by specifying a delegate when creating an . The server can also control validation by supplying a delegate. The method referenced by the delegate includes the remote party's certificate and any errors SSPI encountered while validating the certificate. Note that if the server specifies a delegate, the delegate's method is invoked regardless of whether the server requested client authentication. If the server did not request client authentication, the server's delegate method receives a null certificate and an empty array of certificate errors. + + If the server requires client authentication, the client must specify one or more certificates for authentication. If the client has more than one certificate, the client can provide a delegate to select the correct certificate for the server. The client's certificates must be located in the current user's "My" certificate store. Client authentication via certificates is not supported for the (SSL version 2) protocol. + + If the authentication fails, you receive a , and the is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + + When the authentication process, also known as the SSL handshake, succeeds, the identity of the server (and optionally, the client) is established and the can be used by the client and server to exchange messages. Before sending or receiving information, the client and server should check the security services and levels provided by the to determine whether the protocol, algorithms, and strengths selected meet their requirements for integrity and confidentiality. If the current settings are not sufficient, the stream should be closed. You can check the security services provided by the using the and properties. The following table shows the elements that report the cryptographic settings used for authentication, encryption and data signing. + +|Element|Members| +|-------------|-------------| +|The security protocol used to authenticate the server and, optionally, the client.|The property and the associated enumeration.| +|The key exchange algorithm.|The property and the associated enumeration.| +|The message integrity algorithm.|The property and the associated enumeration.| +|The message confidentiality algorithm.|The property and the associated enumeration.| +|The strengths of the selected algorithms.|The , , and properties.| + + After a successful authentication, you can send data using the synchronous or asynchronous methods. You can receive data using the synchronous or asynchronous methods. + + If you specified to the that the underlying stream should be left open, you are responsible for closing that stream when you are done using it. + > [!NOTE] -> If the application that creates the object runs with the credentials of a Normal user, the application will not be able to access certificates installed in the local machine store unless permission has been explicitly given to the user to do so. - - assumes that a timeout along with any other when one is thrown from the inner stream will be treated as fatal by its caller. Reusing a instance after a timeout will return garbage. An application should the and throw an exception in these cases. - - The .NET Framework 4.6 includes a new security feature that blocks insecure cipher and hashing algorithms for connections. Applications using TLS/SSL through APIs such as HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream, etc. and targeting .NET Framework 4.6 get the more-secure behavior by default. - - Developers may want to opt out of this behavior in order to maintain interoperability with their existing SSL3 services OR TLS w/ RC4 services. [This article](https://support.microsoft.com/kb/3069494) explains how to modify your code so that the new behavior is disabled. - +> If the application that creates the object runs with the credentials of a Normal user, the application will not be able to access certificates installed in the local machine store unless permission has been explicitly given to the user to do so. + + assumes that a timeout along with any other when one is thrown from the inner stream will be treated as fatal by its caller. Reusing a instance after a timeout will return garbage. An application should the and throw an exception in these cases. + + The .NET Framework 4.6 includes a new security feature that blocks insecure cipher and hashing algorithms for connections. Applications using TLS/SSL through APIs such as HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream, etc. and targeting .NET Framework 4.6 get the more-secure behavior by default. + + Developers may want to opt out of this behavior in order to maintain interoperability with their existing SSL3 services OR TLS w/ RC4 services. [This article](https://support.microsoft.com/kb/3069494) explains how to modify your code so that the new behavior is disabled. + The .NET Framework 4.7 adds new overloads for the methods that authenticate SslStreams that do not specify a TLS version, but instead use the TLS version defined as the system default in [SCHANNEL](/windows/win32/secauthn/secure-channel). Use these methods in your app as a way to be able to later modify the defaults as TLS version best practice changes over time, without the need to rebuild and redeploy your app. Also see [Transport Layer Security (TLS) best practices with the .NET Framework](/dotnet/framework/network-programming/tls). - - - -## Examples - The following code example demonstrates creating an that uses the class to communicate with clients. - + + + +## Examples + The following code example demonstrates creating an that uses the class to communicate with clients. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet0"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet0"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet0"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet0"::: - - The following code example demonstrates creating a that uses the class to communicate with a server. - + + The following code example demonstrates creating a that uses the class to communicate with a server. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslClientSync/CPP/clientsync.cpp" id="Snippet0"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/RemoteCertificateValidationCallback/Overview/clientsync.cs" id="Snippet0"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/RemoteCertificateValidationCallback/Overview/clientsync.cs" id="Snippet0"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientSync/VB/clientsync.vb" id="Snippet0"::: ]]> @@ -117,11 +117,11 @@ Initializes a new instance of the class. - from closing the stream that you supply, use the constructor. - + from closing the stream that you supply, use the constructor. + ]]> @@ -168,26 +168,26 @@ A object used by the for sending and receiving data. Initializes a new instance of the class using the specified . - defaults to for the instance that is constructed. - - The use of the Null cipher is required when the encryption policy is set to . - + defaults to for the instance that is constructed. + + The use of the Null cipher is required when the encryption policy is set to . + ]]> - is not readable. - - -or- - + is not readable. + + -or- + is not writable. - is . - - -or- - + is . + + -or- + is equal to . @@ -235,37 +235,37 @@ A Boolean value that indicates the closure behavior of the object used by the for sending and receiving data. This parameter indicates if the inner stream is left open. Initializes a new instance of the class using the specified and stream closure behavior. - has no effect on the `innerStream` stream; you must explicitly close `innerStream` when you no longer need it. - - If a value is not specified in the configuration file for encryptionpolicy, the defaults to for the instance that is constructed. - - The use of the Null cipher is required when the encryption policy is set to . - - - -## Examples - The following code example demonstrates calling this constructor. - + has no effect on the `innerStream` stream; you must explicitly close `innerStream` when you no longer need it. + + If a value is not specified in the configuration file for encryptionpolicy, the defaults to for the instance that is constructed. + + The use of the Null cipher is required when the encryption policy is set to . + + + +## Examples + The following code example demonstrates calling this constructor. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet1"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet1"::: + ]]> - is not readable. - - -or- - + is not readable. + + -or- + is not writable. - is . - - -or- - + is . + + -or- + is equal to . @@ -316,47 +316,47 @@ A delegate responsible for validating the certificate supplied by the remote party. Initializes a new instance of the class using the specified , stream closure behavior and certificate validation delegate. - has no effect on the `innerStream` stream; you must explicitly close `innerStream` when you no longer need it. - - The `userCertificateValidationCallback` delegate's `certificateErrors` argument contains any Windows error codes returned by the channel Security Support Provider Interface (SSPI). The return value of the method invoked by the `userCertificateValidationCallback` delegate determines whether authentication succeeds. - - The security protocol and cryptographic algorithms are already selected when the `userCertificateValidationCallback` delegate's method is invoked. You can use the method to determine whether the selected cryptographic algorithms and strengths are sufficient for your application. If not, the method should return `false` to prevent the from being created. - - If a value is not specified in the configuration file for encryptionpolicy, the defaults to for the instance that is constructed. - - The use of the Null cipher is required when the encryption policy is set to . - + has no effect on the `innerStream` stream; you must explicitly close `innerStream` when you no longer need it. + + The `userCertificateValidationCallback` delegate's `certificateErrors` argument contains any Windows error codes returned by the channel Security Support Provider Interface (SSPI). The return value of the method invoked by the `userCertificateValidationCallback` delegate determines whether authentication succeeds. + + The security protocol and cryptographic algorithms are already selected when the `userCertificateValidationCallback` delegate's method is invoked. You can use the method to determine whether the selected cryptographic algorithms and strengths are sufficient for your application. If not, the method should return `false` to prevent the from being created. + + If a value is not specified in the configuration file for encryptionpolicy, the defaults to for the instance that is constructed. + + The use of the Null cipher is required when the encryption policy is set to . + > [!NOTE] > .NET caches SSL sessions as they are created and attempts to reuse a cached session for subsequent requests, if possible. When attempting to reuse an SSL session, the Framework uses the first element of the provided during authentication (if there is one), or tries to reuse an anonymous sessions if the certificate collection is empty. - + > [!NOTE] -> Client certificates are not supported in the SSL version 2 protocol. - - - -## Examples - The following code example creates an and initiates the client portion of the authentication. - +> Client certificates are not supported in the SSL version 2 protocol. + + + +## Examples + The following code example creates an and initiates the client portion of the authentication. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslClientSync/CPP/clientsync.cpp" id="Snippet4"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/RemoteCertificateValidationCallback/Overview/clientsync.cs" id="Snippet4"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/RemoteCertificateValidationCallback/Overview/clientsync.cs" id="Snippet4"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientSync/VB/clientsync.vb" id="Snippet4"::: - + ]]> - is not readable. - - -or- - + is not readable. + + -or- + is not writable. - is . - - -or- - + is . + + -or- + is equal to . @@ -409,45 +409,45 @@ A delegate responsible for selecting the certificate used for authentication. Initializes a new instance of the class using the specified , stream closure behavior, certificate validation delegate and certificate selection delegate. - has no effect on the `innerStream` stream; you must explicitly close `innerStream` when you no longer need it. - - The `userCertificateValidationCallback` delegate's `certificateErrors` argument contains any Windows error codes returned by the channel Security Support Provider Interface (SSPI). The return value of the method invoked by the `userCertificateValidationCallback` delegate determines whether authentication succeeds. - - The security protocol and cryptographic algorithms are already selected when the `userCertificateValidationCallback` delegate's method is invoked. You can use the method to determine whether the selected cryptographic algorithms and strengths are sufficient for your application. If not, the method should return `false` to prevent the from being created. - - The `userCertificateSelectionCallback` delegate is useful when your application has multiple certificates and must dynamically choose a certificate. Certificates in the "MY" store are passed to the method invoked by the delegate. - - If a value is not specified in the configuration file for encryptionpolicy, the defaults to for the instance that is constructed. - - The use of the Null cipher is required when the encryption policy is set to . - + has no effect on the `innerStream` stream; you must explicitly close `innerStream` when you no longer need it. + + The `userCertificateValidationCallback` delegate's `certificateErrors` argument contains any Windows error codes returned by the channel Security Support Provider Interface (SSPI). The return value of the method invoked by the `userCertificateValidationCallback` delegate determines whether authentication succeeds. + + The security protocol and cryptographic algorithms are already selected when the `userCertificateValidationCallback` delegate's method is invoked. You can use the method to determine whether the selected cryptographic algorithms and strengths are sufficient for your application. If not, the method should return `false` to prevent the from being created. + + The `userCertificateSelectionCallback` delegate is useful when your application has multiple certificates and must dynamically choose a certificate. Certificates in the "MY" store are passed to the method invoked by the delegate. + + If a value is not specified in the configuration file for encryptionpolicy, the defaults to for the instance that is constructed. + + The use of the Null cipher is required when the encryption policy is set to . + > [!NOTE] > .NET caches SSL sessions as they are created and attempts to reuse a cached session for subsequent requests, if possible. When attempting to reuse an SSL session, the Framework uses the first element of the provided during authentication (if there is one), or tries to reuse an anonymous sessions if the certificate collection is empty. - - -## Examples - The following code example demonstrates calling this constructor. This example is part of a larger example provided for the class. - + + +## Examples + The following code example demonstrates calling this constructor. This example is part of a larger example provided for the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslClientAsync/CPP/NclSslClientAsync.cpp" id="Snippet6"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet6"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet6"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet6"::: ]]> - is not readable. - - -or- - + is not readable. + + -or- + is not writable. - is . - - -or- - + is . + + -or- + is equal to . @@ -501,28 +501,28 @@ The to use. Initializes a new instance of the class using the specified . - . - + . + ]]> - is not readable. - - -or- - - is not writable. - - -or- - + is not readable. + + -or- + + is not writable. + + -or- + is not valid. - is . - - -or- - + is . + + -or- + is equal to . @@ -563,15 +563,15 @@ The property bag for the SSL connection. Called by clients to authenticate the server and optionally the client in a client-server connection. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> @@ -627,28 +627,28 @@ The name of the server that shares this . Called by clients to authenticate the server and optionally the client in a client-server connection. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. @@ -693,18 +693,18 @@ A value that specifies whether the certificate revocation list is checked during authentication. Called by clients to authenticate the server and optionally the client in a client-server connection. The authentication process uses the specified certificate collection, and the system default SSL protocol. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + > [!NOTE] -> Client certificates are not supported in the SSL version 2 protocol. - +> Client certificates are not supported in the SSL version 2 protocol. + ]]> @@ -754,18 +754,18 @@ A value that specifies whether the certificate revocation list is checked during authentication. Called by clients to authenticate the server and optionally the client in a client-server connection. The authentication process uses the specified certificate collection and SSL protocol. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + > [!NOTE] -> Client certificates are not supported in the SSL version 2 protocol. - +> Client certificates are not supported in the SSL version 2 protocol. + ]]> @@ -819,15 +819,15 @@ Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. The task object representing the asynchronous operation. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -835,14 +835,14 @@ is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. @@ -882,14 +882,14 @@ Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. The authentication process uses information specified in the property bag. The task object representing the asynchronous operation. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -897,16 +897,17 @@ is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -950,31 +951,31 @@ Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. The authentication process uses the specified certificate collection and the system default SSL protocol. The task object representing the asynchronous operation. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + > [!NOTE] -> Client certificates are not supported in the SSL version 2 protocol. - +> Client certificates are not supported in the SSL version 2 protocol. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. @@ -1025,31 +1026,31 @@ Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. The authentication process uses the specified certificate collection and SSL protocol. The task object representing the asynchronous operation. - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + When authentication succeeds, you must check the and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + > [!NOTE] -> Client certificates are not supported in the SSL version 2 protocol. - +> Client certificates are not supported in the SSL version 2 protocol. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. @@ -1105,14 +1106,14 @@ is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. The method is not supported on Windows 95, Windows 98, or Windows Millennium. @@ -1162,28 +1163,28 @@ The certificate used to authenticate the server. Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificate. - method overloads. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + method overloads. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. The method is not supported on Windows 95, Windows 98, or Windows Millennium. @@ -1228,28 +1229,28 @@ A value that specifies whether the certificate revocation list is checked during authentication. Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates and requirements, and using the system default security protocol. - method overloads. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. The method is not supported on Windows 95, Windows 98, or Windows Millennium. @@ -1299,15 +1300,15 @@ A value that specifies whether the certificate revocation list is checked during authentication. Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates, requirements and security protocol. - method overloads. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + This method blocks until the operation completes. To prevent blocking until the operation completes, use one of the method overloads. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> @@ -1315,14 +1316,14 @@ is not a valid value. The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. The method is not supported on Windows 95, Windows 98, or Windows Millennium. @@ -1377,15 +1378,15 @@ Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificate as an asynchronous operation. The task object representing the asynchronous operation. - . The certificate revocation list is not checked during authentication. The client is not required to provide a certificate for authentication. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + This method authenticates using . The certificate revocation list is not checked during authentication. The client is not required to provide a certificate for authentication. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1393,14 +1394,14 @@ is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. The method is not supported on Windows 95, Windows 98, or Windows Millennium. @@ -1441,12 +1442,12 @@ Called by servers to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. The authentication process uses information specified in the property bag. The task object representing the asynchronous operation. - , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1456,16 +1457,17 @@ is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1499,27 +1501,28 @@ Called by servers to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. The authentication process uses information returned by . The task object representing the asynchronous operation. - , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> Either or or is and is not set in the constructor. The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1562,13 +1565,13 @@ Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates, requirements and security protocol as an asynchronous operation. The task object representing the asynchronous operation. - , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1576,14 +1579,14 @@ is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. @@ -1633,13 +1636,13 @@ Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates, requirements and security protocol as an asynchronous operation. The task object representing the asynchronous operation. - , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1647,14 +1650,14 @@ is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. @@ -1668,11 +1671,11 @@ Begins an operation to authenticate the client side of a client-server connection. - methods. - + methods. + ]]> @@ -1721,34 +1724,34 @@ Called by clients to begin an asynchronous operation to authenticate the server and optionally the client. An object that indicates the status of the asynchronous operation. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. @@ -1798,37 +1801,37 @@ Called by clients to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates and the system default security protocol. An object that indicates the status of the asynchronous operation. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + The value specified for `targetHost` must match the name on the server's certificate. + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + > [!NOTE] -> Client certificates are not supported in the SSL version 2 protocol. - +> Client certificates are not supported in the SSL version 2 protocol. + ]]> is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. @@ -1883,24 +1886,24 @@ Called by clients to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates and security protocol. An object that indicates the status of the asynchronous operation. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + The value specified for `targetHost` must match the name on the server's certificate. + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + > [!NOTE] -> Client certificates are not supported in the SSL version 2 protocol. - +> Client certificates are not supported in the SSL version 2 protocol. + ]]> @@ -1908,14 +1911,14 @@ is not a valid value. The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. @@ -1929,11 +1932,11 @@ Begins an asynchronous operation to handle the server side of authenticating a client-server connection. - methods. - + methods. + ]]> @@ -1988,32 +1991,32 @@ Called by servers to begin an asynchronous operation to authenticate the client and optionally the server in a client-server connection. An object indicating the status of the asynchronous operation. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Client authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Client authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. The method is not supported on Windows 95, Windows 98, or Windows Millennium. @@ -2064,32 +2067,32 @@ Called by servers to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates and requirements, and the system default security protocol. An object that indicates the status of the asynchronous operation. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> is . The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. The method is not supported on Windows 95, Windows 98, or Windows Millennium. @@ -2145,19 +2148,19 @@ Called by servers to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates, requirements and security protocol. An object that indicates the status of the asynchronous operation. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - + + The asynchronous authentication operation must be completed by calling the method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block while the operation completes. To block until the operation completes, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + If you receive a , this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + ]]> @@ -2165,14 +2168,14 @@ is not a valid value. The authentication failed and left this object in an unusable state. - Authentication has already occurred. - - -or- - - Server authentication using this was tried previously. - - -or- - + Authentication has already occurred. + + -or- + + Server authentication using this was tried previously. + + -or- + Authentication is already in progress. This object has been closed. The method is not supported on Windows 95, Windows 98, or Windows Millennium. @@ -2226,38 +2229,38 @@ Begins an asynchronous read operation that reads data from the stream and stores it in the specified array. An object that indicates the status of the asynchronous operation. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block while the operation completes. To block until the operation completes, use the method. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - The class does not support multiple simultaneous read operations. - - You cannot call this method until you have successfully authenticated. To authenticate call one of the , or , , methods. - - - -## Examples - The following code example demonstrates starting an asynchronous read operation. - + method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block while the operation completes. To block until the operation completes, use the method. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + The class does not support multiple simultaneous read operations. + + You cannot call this method until you have successfully authenticated. To authenticate call one of the , or , , methods. + + + +## Examples + The following code example demonstrates starting an asynchronous read operation. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslClientAsync/CPP/NclSslClientAsync.cpp" id="Snippet8"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet8"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet8"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet8"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet8"::: :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslClientAsync/CPP/NclSslClientAsync.cpp" id="Snippet4"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet4"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet4"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet4"::: + + + The following method is called when the read completes. - - The following method is called when the read completes. - :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslClientAsync/CPP/NclSslClientAsync.cpp" id="Snippet5"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet5"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet5"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet5"::: ]]> @@ -2268,15 +2271,15 @@ -or- - is greater than the length of . + is greater than the length of . + +-or- --or- - + count is greater than the length of . - The read operation failed. - - -or- - + The read operation failed. + + -or- + Encryption is in use, but the data could not be decrypted. There is already a read operation in progress. This object has been closed. @@ -2331,27 +2334,27 @@ Begins an asynchronous write operation that writes s from the specified buffer to the stream. An object indicating the status of the asynchronous operation. - is . is less than zero. - + -or- - - is greater than the length of . - + + is greater than the length of . + -or- - + + count is greater than the length of . The write operation failed. There is already a write operation in progress. @@ -2396,20 +2399,20 @@ if authentication has occurred and the underlying stream is readable; otherwise . - on the underlying stream. - - The underlying stream is specified when you create an instance of the class. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + on the underlying stream. + + The underlying stream is specified when you create an instance of the class. + + + +## Examples + The following code example demonstrates displaying the value of this property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet5"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet5"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet5"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet5"::: ]]> @@ -2452,13 +2455,13 @@ Gets a value that indicates whether the underlying stream is seekable. This property always returns . - object or its underlying stream. - - The underlying stream is specified when you create an instance of the class. - + object or its underlying stream. + + The underlying stream is specified when you create an instance of the class. + ]]> @@ -2502,22 +2505,22 @@ if the underlying stream supports time-outs; otherwise, . - on the underlying stream. - - The underlying stream is specified when you create an instance of the class. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + on the underlying stream. + + The underlying stream is specified when you create an instance of the class. + + + +## Examples + The following code example demonstrates displaying the value of this property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet5"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet5"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet5"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet5"::: - + ]]> @@ -2559,22 +2562,22 @@ if authentication has occurred and the underlying stream is writable; otherwise . - on the underlying stream. - - The underlying stream is specified when you create an instance of the class. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + on the underlying stream. + + The underlying stream is specified when you create an instance of the class. + + + +## Examples + The following code example demonstrates displaying the value of this property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet5"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet5"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet5"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet5"::: - + ]]> @@ -2616,20 +2619,20 @@ if the certificate revocation list is checked; otherwise, . - @@ -2670,22 +2673,22 @@ Gets a value that identifies the bulk encryption algorithm used by this . A value that identifies the bulk encryption algorithm used by this . - is required for the property when the enumeration value is used to construct a instance. - - Windows Server 2003 and Windows XP do not support the value. So even if the value is used to construct the instance, the property will be . The value is only returned on Windows Vista and later. - - - -## Examples - The following code example displays the cryptography settings for the specified stream. - + is required for the property when the enumeration value is used to construct a instance. + + Windows Server 2003 and Windows XP do not support the value. So even if the value is used to construct the instance, the property will be . The value is only returned on Windows Vista and later. + + + +## Examples + The following code example displays the cryptography settings for the specified stream. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet3"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet3"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet3"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet3"::: - + ]]> The property was accessed before the completion of the authentication process or the authentication process failed. @@ -2727,38 +2730,38 @@ Gets a value that identifies the strength of the cipher algorithm used by this . An value that specifies the strength of the algorithm, in bits. - @@ -2802,19 +2805,19 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. - - When the `disposing` parameter is true, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - + + When the `disposing` parameter is true, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Overriding the Finalize Method](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ddae83kx(v=vs.100)). @@ -2847,15 +2850,15 @@ Asynchronously releases the unmanaged and managed resources used by the . A task that represents the asynchronous dispose operation. - is `false`; otherwise, the inner stream is just flushed. - + Calling `DisposeAsync` allows the resources used by the to be reallocated for other purposes. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). - + ]]> @@ -2898,15 +2901,15 @@ An instance returned by a call to . Ends a pending asynchronous server authentication operation started with a previous call to . - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - - To perform this operation synchronously, use one of the methods. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + + To perform this operation synchronously, use one of the methods. + ]]> @@ -2955,15 +2958,15 @@ An instance returned by a call to . Ends a pending asynchronous client authentication operation started with a previous call to . - and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. - - If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. - - To perform this operation synchronously, use one of the method. - + and properties to determine what security services are used by the . Check the property to determine whether mutual authentication occurred. + + If the authentication fails, you receive a , and this is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector. + + To perform this operation synchronously, use one of the method. + ]]> @@ -3013,23 +3016,23 @@ Ends an asynchronous read operation started with a previous call to . A value that specifies the number of bytes read from the underlying stream. - method. - - You cannot call this method until you have successfully authenticated. To authenticate call one of the , or , , methods. - - - -## Examples - The following code example demonstrates ending an asynchronous read operation. - + method. + + You cannot call this method until you have successfully authenticated. To authenticate call one of the , or , , methods. + + + +## Examples + The following code example demonstrates ending an asynchronous read operation. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslClientAsync/CPP/NclSslClientAsync.cpp" id="Snippet5"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet5"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/LocalCertificateSelectionCallback/Overview/clientasync.cs" id="Snippet5"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientAsync/VB/clientasync.vb" id="Snippet5"::: ]]> @@ -3083,23 +3086,23 @@ Authentication has not occurred. An instance returned by a call to . Ends an asynchronous write operation started with a previous call to . - , or , , methods. - - To perform this operation synchronously, use the method. - - - -## Examples - The following code example demonstrates ending an asynchronous write operation. - + , or , , methods. + + To perform this operation synchronously, use the method. + + + +## Examples + The following code example demonstrates ending an asynchronous write operation. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerAsync/CPP/NclSslServerAsync.cpp" id="Snippet4"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/BeginWrite/serverasync.cs" id="Snippet4"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/BeginWrite/serverasync.cs" id="Snippet4"::: + ]]> @@ -3185,18 +3188,18 @@ Authentication has not occurred. Causes any buffered data to be written to the underlying device. - on the underlying stream. - - - -## Examples - The following code example demonstrates calling this method. - + on the underlying stream. + + + +## Examples + The following code example demonstrates calling this method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslClientSync/CPP/clientsync.cpp" id="Snippet5"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/RemoteCertificateValidationCallback/Overview/clientsync.cs" id="Snippet5"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/RemoteCertificateValidationCallback/Overview/clientsync.cs" id="Snippet5"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientSync/VB/clientsync.vb" id="Snippet5"::: ]]> @@ -3235,15 +3238,16 @@ Authentication has not occurred. Asynchronously writes any buffered data to the underlying device. A task that represents the asynchronous flush operation. - on the underlying stream. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -3282,20 +3286,20 @@ Authentication has not occurred. Gets the algorithm used for generating message authentication codes (MACs). The algorithm used for generating message authentication codes (MACs). - The property was accessed before the completion of the authentication process or the authentication process failed. @@ -3337,20 +3341,20 @@ Authentication has not occurred. Gets a value that identifies the strength of the hash algorithm used by this instance. An value that specifies the strength of the algorithm, in bits. Valid values are 128 or 160. - @@ -3392,20 +3396,20 @@ Authentication has not occurred. if successful authentication occurred; otherwise, . - or methods. Servers authenticate by calling the or methods. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + or methods. Servers authenticate by calling the or methods. + + + +## Examples + The following code example demonstrates displaying the value of this property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet4"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet4"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet4"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet4"::: - + ]]> @@ -3447,20 +3451,20 @@ Authentication has not occurred. if data is encrypted before being transmitted over the network and decrypted when it reaches the remote endpoint; otherwise . - @@ -3502,20 +3506,20 @@ Authentication has not occurred. if the server has been authenticated; otherwise . - @@ -3559,22 +3563,22 @@ Authentication has not occurred. if the local endpoint was successfully authenticated as the server side of the authenticated connection; otherwise . - or methods. - - - -## Examples - The following code example demonstrates displaying the value of this property. - + or methods. + + + +## Examples + The following code example demonstrates displaying the value of this property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet4"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet4"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet4"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet4"::: - + ]]> @@ -3616,20 +3620,20 @@ Authentication has not occurred. if the data is signed before being transmitted; otherwise . - @@ -3670,22 +3674,22 @@ Authentication has not occurred. Gets the key exchange algorithm used by this . An value. - until the authentication occurs. - - The key exchange algorithm protects information used to generate shared keys. - - - -## Examples - The following code example displays the cryptography settings for the specified stream. - + until the authentication occurs. + + The key exchange algorithm protects information used to generate shared keys. + + + +## Examples + The following code example displays the cryptography settings for the specified stream. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet3"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet3"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet3"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet3"::: - + ]]> @@ -3726,29 +3730,29 @@ Authentication has not occurred. Gets a value that identifies the strength of the key exchange algorithm used by this instance. An value that specifies the strength of the algorithm, in bits. - @@ -3790,11 +3794,11 @@ Authentication has not occurred. Gets the length of the underlying stream. The length of the underlying stream. - on the underlying stream. If the underlying stream is not seekable, this method typically throws an exception. The run-time type of the underlying stream determines the run-time type of the exception that is thrown. - + on the underlying stream. If the underlying stream is not seekable, this method typically throws an exception. The run-time type of the underlying stream determines the run-time type of the exception that is thrown. + ]]> Getting the value of this property is not supported when the underlying stream is a . @@ -3837,15 +3841,15 @@ Authentication has not occurred.
Gets the certificate used to authenticate the local endpoint. An X509Certificate object that represents the certificate supplied for authentication or if no certificate was supplied. - Authentication failed or has not occurred. @@ -3877,6 +3881,7 @@ Authentication has not occurred.
Negotiates the client certificate on the authenticated connection. The task object representing the asynchronous operation. You can negotiate the client certificate once authentication is successfully processed via one of the AuthenticateAs... methods. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3940,8 +3945,8 @@ Authentication has not occurred.
Gets the cipher suite which was negotiated for this connection. One of the enumeration values that identifies the cipher suite which was negotiated for this connection. - or . @@ -3987,17 +3992,17 @@ This property gets the cipher suite that is going to be used in the communicatio Gets or sets the current position in the underlying stream. The current position in the underlying stream. - on the underlying stream. If the underlying stream is not seekable, this method typically throws an exception. The run-time type of the underlying stream determines the run-time type of the exception that is thrown. - + on the underlying stream. If the underlying stream is not seekable, this method typically throws an exception. The run-time type of the underlying stream determines the run-time type of the exception that is thrown. + ]]> - Setting this property is not supported. - - -or- - + Setting this property is not supported. + + -or- + Getting the value of this property is not supported when the underlying stream is a . @@ -4045,22 +4050,22 @@ This property gets the cipher suite that is going to be used in the communicatio Reads data from this stream and stores it in the specified array. A value that specifies the number of bytes read. When there is no more data to be read, returns 0. - , or , , methods. - - To perform this operation asynchronously, use the method. - - - -## Examples - The following code example demonstrates reading from an . - + , or , , methods. + + To perform this operation asynchronously, use the method. + + + +## Examples + The following code example demonstrates reading from an . + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslClientSync/CPP/clientsync.cpp" id="Snippet6"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Security/RemoteCertificateValidationCallback/Overview/clientsync.cs" id="Snippet6"::: + :::code language="csharp" source="~/snippets/csharp/System.Net.Security/RemoteCertificateValidationCallback/Overview/clientsync.cs" id="Snippet6"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslClientSync/VB/clientsync.vb" id="Snippet6"::: ]]> @@ -4069,12 +4074,12 @@ This property gets the cipher suite that is going to be used in the communicatio is . is less than zero. - + -or- - is greater than the length of . + is greater than the length of . --or- +-or- + count is greater than the length of . The read operation failed. Check the inner exception, if present to determine the cause of the failure. @@ -4115,13 +4120,13 @@ This property gets the cipher suite that is going to be used in the communicatio Asynchronously reads data from this stream and stores it in the specified memory range. A task that represents the asynchronous read operation. The value of its property contains the total number of bytes read into . When there is no more data to be read, returns 0. - @@ -4130,6 +4135,7 @@ This property gets the cipher suite that is going to be used in the communicatio The read operation failed. Check the inner exception, if it is present, to determine the cause of the failure. There is already a read operation in progress. This object has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -4169,13 +4175,13 @@ This property gets the cipher suite that is going to be used in the communicatio Asynchronously reads data from this stream and stores it in the specified range of a byte array. A task that represents the asynchronous read operation. The value of its property contains the total number of bytes read into . When there is no more data to be read, returns 0. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . @@ -4185,19 +4191,20 @@ This property gets the cipher suite that is going to be used in the communicatio is . - is less than 0. - - -or- - + is less than 0. + + -or- + is less than 0. - - -or- - + + -or- + is greater than the length of minus . Authentication has not occurred. The read operation failed. Check the inner exception, if it is present, to determine the cause of the failure. There is already a read operation in progress. This object has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -4228,11 +4235,11 @@ This property gets the cipher suite that is going to be used in the communicatio Reads a byte from the and advances the position within the stream by one byte, or returns -1 if at the end of the stream. The unsigned byte cast to an , or -1 if at the end of the stream. - @@ -4279,22 +4286,22 @@ This property gets the cipher suite that is going to be used in the communicatio Gets or sets the amount of time, expressed in milliseconds, a read operation blocks waiting for data. The amount of time, in milliseconds, that elapses before a synchronous read operation fails. - on the underlying stream. When you set this property, the value on the underlying stream is set to the specified value. - - If the underlying stream is a , is in milliseconds and is set to by default so that read operations do not timeout. - - - -## Examples - The following code example demonstrates setting the value of this property. - + on the underlying stream. When you set this property, the value on the underlying stream is set to the specified value. + + If the underlying stream is a , is in milliseconds and is set to by default so that read operations do not timeout. + + + +## Examples + The following code example demonstrates setting the value of this property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet1"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet1"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet1"::: - + ]]> @@ -4336,16 +4343,16 @@ This property gets the cipher suite that is going to be used in the communicatio Gets the certificate used to authenticate the remote endpoint. An X509Certificate object that represents the certificate supplied for authentication or if no certificate was supplied. - object. - -## Examples - The following code example demonstrates displaying the certificate returned by this property. - + +## Examples + The following code example demonstrates displaying the certificate returned by this property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet6"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet6"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet6"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet6"::: - + ]]> Authentication failed or has not occurred. @@ -4393,11 +4400,11 @@ If the property is accessed, the remote certificate will not be disposed when th Throws a . Always throws a . - class. - + class. + ]]> Seeking is not supported by objects. @@ -4442,11 +4449,11 @@ If the property is accessed, the remote certificate will not be disposed when th An value that specifies the length of the stream. Sets the length of the underlying stream. - on the underlying stream specified when this was created. - + on the underlying stream specified when this was created. + ]]> @@ -4522,21 +4529,21 @@ If the property is accessed, the remote certificate will not be disposed when th Gets a value that indicates the security protocol used to authenticate this connection. The value that represents protocols used for authentication. - or via and or . If no security protocol was explicitly specified, the value is used. - - The actual protocol used for authentication is selected based on the ones supported by the client and server. - - -## Examples - The following example displays the security properties of the specified stream. - + + The actual protocol used for authentication is selected based on the ones supported by the client and server. + + +## Examples + The following example displays the security properties of the specified stream. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet3"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet3"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet3"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet3"::: - + ]]> @@ -4658,24 +4665,24 @@ If the property is accessed, the remote certificate will not be disposed when th A array that supplies the bytes written to the stream. Writes the specified data to this stream. - method. - - You cannot call this method until you have successfully authenticated. To authenticate call one of the , or , , methods. - - The class does not support multiple simultaneous write operations. - - - -## Examples - The following code example demonstrates writing to an authenticated . - + method. + + You cannot call this method until you have successfully authenticated. To authenticate call one of the , or , , methods. + + The class does not support multiple simultaneous write operations. + + + +## Examples + The following code example demonstrates writing to an authenticated . + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet1"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet1"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet1"::: - + ]]> @@ -4729,15 +4736,15 @@ If the property is accessed, the remote certificate will not be disposed when th A that contains the number of bytes to read from . Write the specified number of s to the underlying stream using the specified buffer and offset. - method. - - You cannot call this method until you have successfully authenticated. To authenticate call one of the , or , , methods. - - The class does not support multiple simultaneous write operations. - + method. + + You cannot call this method until you have successfully authenticated. To authenticate call one of the , or , , methods. + + The class does not support multiple simultaneous write operations. + ]]> @@ -4747,10 +4754,10 @@ If the property is accessed, the remote certificate will not be disposed when th -or- - is greater than the length of . - - -or- - + is greater than the length of . + + -or- + + count is greater than the length of . The write operation failed. There is already a write operation in progress. @@ -4790,10 +4797,10 @@ If the property is accessed, the remote certificate will not be disposed when th Asynchronously writes data to the underlying stream from a read-only byte memory range. A task that represents the asynchronous write operation. - class does not support multiple simultaneous write operations. @@ -4803,6 +4810,7 @@ The class does not support multiple simulta The write operation failed. There is already a write operation in progress. This object has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -4842,10 +4850,10 @@ The class does not support multiple simulta Asynchronously writes data to the underlying stream from the specified range of a byte array. A task that represents the asynchronous write operation. - class does not support multiple simultaneous write operations. @@ -4856,19 +4864,20 @@ The class does not support multiple simulta is . - is less than 0. - - -or- - + is less than 0. + + -or- + is less than 0. - - -or- - + + -or- + is greater than the length of minus . Authentication has not occurred. The write operation failed. There is already a write operation in progress. This object has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -4907,22 +4916,22 @@ The class does not support multiple simulta Gets or sets the amount of time a write operation blocks waiting for data. The amount of time that elapses before a synchronous write operation fails. - on the underlying stream. For set operations, the specified value sets the value on the underlying stream. - - If the underlying stream is a , is in milliseconds and is set to by default so that write operations do not timeout. - - - -## Examples - The following code example demonstrates setting the value of this property. - + on the underlying stream. For set operations, the specified value sets the value on the underlying stream. + + If the underlying stream is a , is in milliseconds and is set to by default so that write operations do not timeout. + + + +## Examples + The following code example demonstrates setting the value of this property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclSslServerSync/CPP/NclSslServerSync.cpp" id="Snippet1"::: -:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet1"::: +:::code language="csharp" source="~/snippets/csharp/System.Net.Security/SslStream/Overview/serversync.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NclSslServerSync/VB/serversync.vb" id="Snippet1"::: - + ]]> diff --git a/xml/System.Net.Sockets/NetworkStream.xml b/xml/System.Net.Sockets/NetworkStream.xml index beaef1fe799..3eb25a134e5 100644 --- a/xml/System.Net.Sockets/NetworkStream.xml +++ b/xml/System.Net.Sockets/NetworkStream.xml @@ -45,19 +45,19 @@ Provides the underlying stream of data for network access. - class provides methods for sending and receiving data over sockets in blocking mode. For more information about blocking versus nonblocking s, see [Using an Asynchronous Client Socket](/dotnet/framework/network-programming/using-an-asynchronous-client-socket). You can use the class for both synchronous and asynchronous data transfer. For more information about synchronous and asynchronous communication, see [Sockets](/dotnet/framework/network-programming/sockets). - - To create a , you must provide a connected . You can also specify what permission the has over the provided . By default, closing the does not close the provided . If you want the to have permission to close the provided , you must specify `true` for the value of the `ownsSocket` parameter. - - Use the and methods for simple single threaded synchronous blocking I/O. If you want to process your I/O asynchronously, consider using the or -based methods and . - - The does not support random access to the network data stream. The value of the property, which indicates whether the stream supports seeking, is always `false`; reading the property, reading the property, or calling the method will throw a . - - Read and write operations can be performed simultaneously on an instance of the class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required. - + class provides methods for sending and receiving data over sockets in blocking mode. For more information about blocking versus nonblocking s, see [Using an Asynchronous Client Socket](/dotnet/framework/network-programming/using-an-asynchronous-client-socket). You can use the class for both synchronous and asynchronous data transfer. For more information about synchronous and asynchronous communication, see [Sockets](/dotnet/framework/network-programming/sockets). + + To create a , you must provide a connected . You can also specify what permission the has over the provided . By default, closing the does not close the provided . If you want the to have permission to close the provided , you must specify `true` for the value of the `ownsSocket` parameter. + + Use the and methods for simple single threaded synchronous blocking I/O. If you want to process your I/O asynchronously, consider using the or -based methods and . + + The does not support random access to the network data stream. The value of the property, which indicates whether the stream supports seeking, is always `false`; reading the property, reading the property, or calling the method will throw a . + + Read and write operations can be performed simultaneously on an instance of the class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required. + ]]> @@ -111,24 +111,24 @@ The that the will use to send and receive data. Creates a new instance of the class for the specified . - is created with read/write access to the specified . - The does not own the underlying , so calling the or method does not close the . - + The does not own the underlying , so calling the or method does not close the . + ]]> The parameter is . - The parameter is not connected. - - -or- - - The property of the parameter is not . - - -or- - + The parameter is not connected. + + -or- + + The property of the parameter is not . + + -or- + The parameter is in a nonblocking state. Using Streams on the Network @@ -173,23 +173,23 @@ Set to to indicate that the will take ownership of the ; otherwise, . Initializes a new instance of the class for the specified with the specified ownership. - is created with read/write access to the specified . If the value of `ownsSocket` parameter is `true`, the takes ownership of the underlying , and calling the or method also closes the underlying . ]]> The parameter is . - The parameter is not connected. - - -or- - - the value of the property of the parameter is not . - - -or- - + The parameter is not connected. + + -or- + + the value of the property of the parameter is not . + + -or- + the parameter is in a nonblocking state. @@ -232,25 +232,25 @@ A bitwise combination of the values that specify the type of access given to the over the provided . Creates a new instance of the class for the specified with the specified access rights. - is created with the specified access to the specified . With this constructor, the does not own the underlying , so calling the or method does not close the underlying . - - The `access` parameter sets the and properties of the . If you specify , then the allows calls to the method. If you specify , then the allows calls to the method. If you specify , both method calls are allowed. + + The `access` parameter sets the and properties of the . If you specify , then the allows calls to the method. If you specify , then the allows calls to the method. If you specify , both method calls are allowed. ]]> The parameter is . - The parameter is not connected. - - -or- - - the property of the parameter is not . - - -or- - + The parameter is not connected. + + -or- + + the property of the parameter is not . + + -or- + the parameter is in a nonblocking state. @@ -300,25 +300,25 @@ Set to to indicate that the will take ownership of the ; otherwise, . Creates a new instance of the class for the specified with the specified access rights and the specified ownership. - is created with read/write access to the specified . If the value of the `ownsSocket` parameter is `true`, the takes ownership of the underlying , and calling the or method also closes the underlying . - - The `access` parameter sets the and properties of the . If you specify , then the allows calls to the method. If you specify , then the allows calls to the method. If you specify , both method calls are allowed. + + The `access` parameter sets the and properties of the . If you specify , then the allows calls to the method. If you specify , then the allows calls to the method. If you specify , both method calls are allowed. ]]> The parameter is . - The parameter is not connected. - - -or- - - The property of the parameter is not . - - -or- - + The parameter is not connected. + + -or- + + The property of the parameter is not . + + -or- + The parameter is in a nonblocking state. @@ -384,47 +384,47 @@ Begins an asynchronous read from the . An that represents the asynchronous call. - [!IMPORTANT] > This is a compatibility API, we don't recommend to use the [APM](/dotnet/standard/asynchronous-programming-patterns/asynchronous-programming-model-apm) (Begin / End) methods for new development. Instead, use the Task-based equivalents. You can pass a callback that implements to in order to get notified about the completion of the operation. Note that if the underlying network stack completes the operation synchronously, the callback will be executed inline, during the call to . In this case, the property on the returned will be set to `true` to indicate that the method completed synchronously. Use the property of the to obtain the state object passed to the method. - The operation must be completed by calling the method. Typically, the method is invoked by the provided delegate. will block the calling thread until the operation is completed. - - The operation reads as much data as is available, up to the number of bytes specified by the `size` parameter. - + The operation must be completed by calling the method. Typically, the method is invoked by the provided delegate. will block the calling thread until the operation is completed. + + The operation reads as much data as is available, up to the number of bytes specified by the `size` parameter. + > [!NOTE] -> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code. +> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code. Read and write operations can be performed simultaneously on an instance of the class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required. ]]> The parameter is . - The parameter is less than 0. - - -or- - - The parameter is greater than the length of the paramater. - - -or- - - The is less than 0. - - -or- - + The parameter is less than 0. + + -or- + + The parameter is greater than the length of the paramater. + + -or- + + The is less than 0. + + -or- + The is greater than the length of minus the value of the parameter. - The underlying is closed. - - -or- - - There was a failure while reading from the network. - - -or- - + The underlying is closed. + + -or- + + There was a failure while reading from the network. + + -or- + An error occurred when accessing the socket. The is closed. @@ -486,45 +486,45 @@ Begins an asynchronous write to a stream. An that represents the asynchronous call. - [!IMPORTANT] > This is a compatibility API, we don't recommend to use the [APM](/dotnet/standard/asynchronous-programming-patterns/asynchronous-programming-model-apm) (Begin / End) methods for new development. Instead, use the Task-based equivalents. You can pass a callback that implements to in order to get notified about the completion of the operation. Note that if the underlying network stack completes the operation synchronously, the callback will be executed inline, during the call to . In this case, the property on the returned will be set to `true` to indicate that the method completed synchronously. Use the property of the to obtain the state object passed to the method. - The operation must be completed by calling the method. Typically, the method is invoked by the provided delegate. will block the calling thread until the operation is completed. - + The operation must be completed by calling the method. Typically, the method is invoked by the provided delegate. will block the calling thread until the operation is completed. + > [!NOTE] -> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code. - +> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code. + Read and write operations can be performed simultaneously on an instance of the class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required. - + ]]> The parameter is . - The parameter is less than 0. - - -or- - - The parameter is greater than the length of . - - -or- - - The parameter is less than 0. - - -or- - + The parameter is less than 0. + + -or- + + The parameter is greater than the length of . + + -or- + + The parameter is less than 0. + + -or- + The parameter is greater than the length of minus the value of the parameter. - The underlying is closed. - - -or- - - There was a failure while writing to the network. - - -or- - + The underlying is closed. + + -or- + + There was a failure while writing to the network. + + -or- + An error occurred when accessing the socket. The is closed. @@ -574,11 +574,11 @@ if data can be read from the stream; otherwise, . The default value is . - is `true`, allows calls to the method. Provide the appropriate enumerated value in the constructor to set the readability and writability of the . - + > [!NOTE] > The property is set when the is initialized. > Changes in the underlying 's state (eg. closure) do not affect the value of . @@ -666,11 +666,11 @@ in all cases. - . - + . + ]]> @@ -719,14 +719,14 @@ if data can be written to the ; otherwise, . The default value is . - is `true`, allows calls to the method. Provide the appropriate enumerated value in the constructor to set the readability and writability of the . - + > [!NOTE] > The property is set when the is initialized. -> Changes in the underlying 's state (eg. closure) do not affect the value of . +> Changes in the underlying 's state (eg. closure) do not affect the value of . ]]> @@ -761,12 +761,12 @@ . If the owns the underlying , it is closed as well. If a was associated with a , the `Close` method will close the TCP connection, but not dispose of the associated . -## Examples +## Examples The following code example closes the . ```vb @@ -830,13 +830,13 @@ myNetworkStream->Close(); A 32-bit signed integer that specifies the number of milliseconds to wait to send any remaining data before closing. Closes the after waiting the specified time to allow data to be sent. - method frees both unmanaged and managed resources associated with the . If the owns the underlying , it is closed as well. - - If a was associated with a , the method will close the TCP connection, but not dispose of the associated . - + method frees both unmanaged and managed resources associated with the . If the owns the underlying , it is closed as well. + + If a was associated with a , the method will close the TCP connection, but not dispose of the associated . + ]]> The parameter is less than -1. @@ -920,10 +920,10 @@ The Close method frees both unmanaged and managed resources associated with the if data is available on the stream to be read; otherwise, . - property to determine if data is queued to be immediately read. + property to determine if data is queued to be immediately read. If is `true`, a call to returns immediately. If the remote host shuts down or closes the connection, may throw a . @@ -984,19 +984,19 @@ The Close method frees both unmanaged and managed resources associated with the to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose` method of each referenced object. - + This method is called by the public `Dispose()` method and the method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose` method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Overriding the Finalize Method](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ddae83kx(v=vs.100)). @@ -1041,26 +1041,26 @@ The Close method frees both unmanaged and managed resources associated with the Handles the end of an asynchronous read. The number of bytes read from the . - [!IMPORTANT] > This is a compatibility API, we don't recommend to use the [APM](/dotnet/standard/asynchronous-programming-patterns/asynchronous-programming-model-apm) (Begin / End) methods for new development. Instead, use the Task-based equivalents. - The method completes the read operation started by the method. You need to pass the created by the matching call. will block the calling thread until the operation is completed. - - The operation reads as much data as is available, up to the number of bytes specified by the `size` parameter. - + The method completes the read operation started by the method. You need to pass the created by the matching call. will block the calling thread until the operation is completed. + + The operation reads as much data as is available, up to the number of bytes specified by the `size` parameter. + > [!NOTE] -> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code. +> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code. ]]> The parameter is . - The underlying is closed. - - -or- - + The underlying is closed. + + -or- + An error occurred when accessing the socket. The is closed. @@ -1105,30 +1105,30 @@ The Close method frees both unmanaged and managed resources associated with the The that represents the asynchronous call. Handles the end of an asynchronous write. - [!IMPORTANT] > This is a compatibility API, we don't recommend to use the [APM](/dotnet/standard/asynchronous-programming-patterns/asynchronous-programming-model-apm) (Begin / End) methods for new development. Instead, use the Task-based equivalents. - The method completes the read operation started by the method. You need to pass the created by the matching call. will block the calling thread until the operation is completed. - - The operation reads as much data as is available, up to the number of bytes specified by the `size` parameter. - + The method completes the read operation started by the method. You need to pass the created by the matching call. will block the calling thread until the operation is completed. + + The operation reads as much data as is available, up to the number of bytes specified by the `size` parameter. + > [!NOTE] -> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code. +> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code. ]]> The parameter is . - The underlying is closed. - - -or- - - An error occurred while writing to the network. - - -or- - + The underlying is closed. + + -or- + + An error occurred while writing to the network. + + -or- + An error occurred when accessing the socket. The is closed. @@ -1171,13 +1171,13 @@ The Close method frees both unmanaged and managed resources associated with the Releases all resources used by the . - . Application code should not call this method; an object's method is automatically invoked during garbage collection, unless finalization by the garbage collector has been disabled by a call to the method. - - For more information about using the Finalize method, see [Finalize Methods and Destructors](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/0s71x931(v%3dvs.100)), [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged), and [Overriding the Finalize Method](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ddae83kx(v=vs.100)). - + . Application code should not call this method; an object's method is automatically invoked during garbage collection, unless finalization by the garbage collector has been disabled by a call to the method. + + For more information about using the Finalize method, see [Finalize Methods and Destructors](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/0s71x931(v%3dvs.100)), [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged), and [Overriding the Finalize Method](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ddae83kx(v=vs.100)). + ]]> @@ -1219,11 +1219,11 @@ The Close method frees both unmanaged and managed resources associated with the Flushes data from the stream. This method is reserved for future use. - method implements the method; however, because is not buffered, it has no effect on network streams. Calling the method does not throw an exception. - + method implements the method; however, because is not buffered, it has no effect on network streams. Calling the method does not throw an exception. + ]]> @@ -1267,15 +1267,16 @@ The Close method frees both unmanaged and managed resources associated with the Flushes data from the stream as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after data has been flushed from the stream for the instance. - + object will complete after data has been flushed from the stream for the instance. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1389,17 +1390,17 @@ The Close method frees both unmanaged and managed resources associated with the Reads data from the and stores it to a span of bytes in memory. The number of bytes read from the . - [!NOTE] -> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . - +> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . + > [!NOTE] -> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + ]]> The does not support reading. @@ -1464,40 +1465,40 @@ There is a failure reading from the network.
Reads data from the and stores it to a byte array. The number of bytes read from the . - [!NOTE] -> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . - +> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . + > [!NOTE] -> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. +> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + +## Examples + The following code example uses to determine if data is available to be read. If data is available, it reads from the . - -## Examples - The following code example uses to determine if data is available to be read. If data is available, it reads from the . - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/Overview/source.cs" id="Snippet4"::: - + ]]> is . - is less than 0. - - -or- - - is greater than the length of . - - -or- - - is less than 0. - - -or- - + is less than 0. + + -or- + + is greater than the length of . + + -or- + + is less than 0. + + -or- + is greater than the length of minus . The does not support reading. An error occurred when accessing the socket. @@ -1559,22 +1560,22 @@ There is a failure reading from the network. to indicate that the can be read; otherwise, . The default value is . - class to use the property. If is `true`, allows calls to the method. You can also determine whether a is readable by checking the publicly accessible property. - - The property is set when the is initialized. - - - -## Examples - In the following code example, the `CanCommunicate` property checks the property to determine if the is readable. - + class to use the property. If is `true`, allows calls to the method. You can also determine whether a is readable by checking the publicly accessible property. + + The property is set when the is initialized. + + + +## Examples + In the following code example, the `CanCommunicate` property checks the property to determine if the is readable. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NetworkStream_Protected_Members/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/Readable/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NetworkStream_Protected_Members/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NetworkStream_Protected_Members/VB/source.vb" id="Snippet1"::: + ]]> @@ -1614,17 +1615,17 @@ There is a failure reading from the network.
Reads data from the and stores it in a byte memory range as an asynchronous operation. A that represents the asynchronous read operation. The value of its property contains the total number of bytes read into . - [!NOTE] -> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . - +> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . + > [!NOTE] -> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + ]]> The does not support reading. @@ -1634,6 +1635,7 @@ This method reads as much data as is available into `buffer` and returns the num There is a failure reading from the network.
The is closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1682,17 +1684,17 @@ There is a failure reading from the network.
Reads data from the and stores it to a specified range of a byte array as an asynchronous operation. A task that represents the asynchronous read operation. The value of its property contains the total number of bytes read into . - [!NOTE] -> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . - +> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . + > [!NOTE] -> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1704,6 +1706,7 @@ There is a failure reading from the network.
There is a failure reading from the network.
The is closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1734,16 +1737,16 @@ There is a failure reading from the network.
Reads a byte from the and advances the position within the stream by one byte, or returns -1 if at the end of the stream. The unsigned byte cast to an , or -1 if at the end of the stream. - [!NOTE] -> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . - +> Check to see if the is readable by calling the property. If you attempt to read from a that is not readable, you will get an . + > [!NOTE] -> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + ]]> The does not support reading. @@ -1791,20 +1794,20 @@ There is a failure reading from the network.
Gets or sets the amount of time that a read operation blocks waiting for data. A that specifies the amount of time, in milliseconds, that will elapse before a read operation fails. The default value, , specifies that the read operation does not time out. - . - + . + > [!NOTE] > This property affects only synchronous reads performed by calling the method. This property does not affect asynchronous reads performed by calling the or method. - - -## Examples - The following code example sets the read time-out for a network stream to 10 milliseconds. - - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/ReadTimeout/tcpclient.cs" id="Snippet2"::: - + + +## Examples + The following code example sets the read time-out for a network stream to 10 milliseconds. + + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/ReadTimeout/tcpclient.cs" id="Snippet2"::: + ]]> The value specified is less than or equal to zero and is not . @@ -1944,23 +1947,23 @@ There is a failure reading from the network.
Gets the underlying . A that represents the underlying network connection. - can use this property to get the underlying . Use the underlying returned from the property if you require access beyond that which provides. - + can use this property to get the underlying . Use the underlying returned from the property if you require access beyond that which provides. + > [!NOTE] -> This property is accessible only through this class or a derived class. - - - -## Examples - The following code example retrieves the underlying to verify an active connection. - +> This property is accessible only through this class or a derived class. + + + +## Examples + The following code example retrieves the underlying to verify an active connection. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NetworkStream_Protected_Members/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/Readable/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NetworkStream_Protected_Members/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NetworkStream_Protected_Members/VB/source.vb" id="Snippet1"::: + ]]> @@ -1995,7 +1998,7 @@ There is a failure reading from the network.
. The `Dispose` method leaves the in an unusable state. After calling `Dispose`, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. For more information about using the Dispose method, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). > [!NOTE] @@ -2038,7 +2041,7 @@ Call `Dispose` when you are finished using the is thrown. > [!NOTE] @@ -2109,40 +2112,40 @@ There was a failure while writing to the network.
The number of bytes to write to the . Writes data to the from a specified range of a byte array. - is thrown. - + is thrown. + > [!NOTE] > Check to see if the is writable by calling the property. If you attempt to write to a that is not writable, you will get an . > [!NOTE] > If you receive an , check the property to determine if it was caused by a . If so, use the property to obtain the specific error code and refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error. - -## Examples - The following code example checks to see whether the is writable. If it is, then is used to write a small message. - + +## Examples + The following code example checks to see whether the is writable. If it is, then is used to write a small message. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NetworkStream_Synch_SendAndReceive/CPP/source.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/Overview/source.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NetworkStream_Synch_SendAndReceive/VB/source.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NetworkStream_Synch_SendAndReceive/VB/source.vb" id="Snippet3"::: + ]]> The parameter is . - The parameter is less than 0. - - -or- - - The parameter is greater than the length of . - - -or- - - The parameter is less than 0. - - -or- - + The parameter is less than 0. + + -or- + + The parameter is greater than the length of . + + -or- + + The parameter is less than 0. + + -or- + The parameter is greater than the length of minus the value of the parameter. The does not support writing. An error occurred when accessing the socket. @@ -2202,22 +2205,22 @@ There was a failure while writing to the network. if data can be written to the stream; otherwise, . The default value is . - class to use the property. If is `true`, allows calls to the method. You can also determine whether a is writable by checking the publicly accessible property. - - The property is set when the is initialized. - - - -## Examples - In the following code example, the `CanCommunicate` property checks the property to determine if the is writable. - + class to use the property. If is `true`, allows calls to the method. You can also determine whether a is writable by checking the publicly accessible property. + + The property is set when the is initialized. + + + +## Examples + In the following code example, the `CanCommunicate` property checks the property to determine if the is writable. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NetworkStream_Protected_Members/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/Readable/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NetworkStream_Protected_Members/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/NetworkStream_Protected_Members/VB/source.vb" id="Snippet1"::: + ]]> @@ -2257,7 +2260,7 @@ There was a failure while writing to the network. A task that represents the asynchronous write operation. [!NOTE] @@ -2275,6 +2278,7 @@ This method sends all bytes in `buffer` to the network. There was a failure while writing to the network.
The is closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2324,7 +2328,7 @@ There was a failure while writing to the network.
A task that represents the asynchronous write operation. [!NOTE] @@ -2338,26 +2342,27 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> The parameter is . - The parameter is less than 0. - - -or- - - The parameter is greater than the length of . - - -or- - - The parameter is less than 0. - - -or- - + The parameter is less than 0. + + -or- + + The parameter is greater than the length of . + + -or- + + The parameter is less than 0. + + -or- + The parameter is greater than the length of minus the value of the parameter. The does not support writing. - There was a failure while writing to the network. - - -or- - + There was a failure while writing to the network. + + -or- + An error occurred when accessing the socket. The is closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2445,22 +2450,22 @@ There was a failure while writing to the network. Gets or sets the amount of time that a write operation blocks waiting for data. A that specifies the amount of time, in milliseconds, that will elapse before a write operation fails. The default value, , specifies that the write operation does not time out. - . - + . + > [!NOTE] > This property affects only synchronous write operations performed by calling the method. This property does not affect asynchronous writes performed by calling the or method. - - - -## Examples - The following code example sets the write time-out for a network stream to 10 milliseconds. - + + + +## Examples + The following code example sets the write time-out for a network stream to 10 milliseconds. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NclTcpServerSync/cpp/tcplistener.cpp" id="Snippet0"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/WriteTimeout/tcplistener.cs" id="Snippet0"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/WriteTimeout/tcplistener.cs" id="Snippet0"::: + ]]> The value specified is less than or equal to zero and is not . diff --git a/xml/System.Net.Sockets/Socket.xml b/xml/System.Net.Sockets/Socket.xml index 97bad457c62..62b9a29cbdb 100644 --- a/xml/System.Net.Sockets/Socket.xml +++ b/xml/System.Net.Sockets/Socket.xml @@ -79,12 +79,12 @@ ### Synchronous mode The following example shows how the class can be used to send data to an HTTP server, printing the ASCII response to the standard output. This example blocks the calling thread until the entire page is received. - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/Socket/Overview/socket.cs" id="Snippet1"::: ### Asynchronous mode The second example demonstrates the same HTTP GET scenario, using Task-based asynchronous API-s, while also forwarding a to the asynchronous methods, making the entire operation cancellable. - + > [!TIP] > 's async methods that do not take a typically return a , which is allocated on the heap. > Cancellable overloads are always -returning; using them helps reducing allocations in high-performance code. @@ -636,6 +636,7 @@ This method populates the instance with data ga This exception also occurs if the socket is already connected or a socket operation was already in progress using the specified parameter. An error occurred when attempting to access the socket. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -680,6 +681,7 @@ This method populates the instance with data ga This exception also occurs if the socket is already connected or a socket operation was already in progress using the specified parameter.
An error occurred when attempting to access the socket. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2897,7 +2899,7 @@ This method populates the instance with data ga You can pass a callback that implements to in order to get notified about the completion of the operation. Note that if the underlying network stack completes the operation synchronously, the callback will be executed inline, during the call to . In this case, the property on the returned will be set to `true` to indicate that the method completed synchronously. Use the property of the to obtain the state object passed to the method. - The operation must be completed by calling the method. Typically, the method is invoked by the delegate. will block the calling thread until the operation is completed. + The operation must be completed by calling the method. Typically, the method is invoked by the delegate. will block the calling thread until the operation is completed. Although intended for connection-oriented protocols, also works for connectionless protocols, provided that you first call the or method to establish a default remote host. With connectionless protocols, you must be sure that the size of your file does not exceed the maximum packet size of the underlying service provider. If it does, the datagram is not sent and throws a exception. @@ -2989,7 +2991,7 @@ This method populates the instance with data ga You can pass a callback that implements to in order to get notified about the completion of the operation. Note that if the underlying network stack completes the operation synchronously, the callback will be executed inline, during the call to . In this case, the property on the returned will be set to `true` to indicate that the method completed synchronously. Use the property of the to obtain the state object passed to the method. - The operation must be completed by calling the method. Typically, the method is invoked by the provided delegate. will block the calling thread until the operation is completed. + The operation must be completed by calling the method. Typically, the method is invoked by the provided delegate. will block the calling thread until the operation is completed. Although intended for connection-oriented protocols, also works for connectionless protocols, provided that you first call the or method to establish a default remote host. With connectionless protocols, you must be sure that the size of your file does not exceed the maximum packet size of the underlying service provider. If it does, the datagram is not sent and throws a exception. @@ -3093,7 +3095,7 @@ This method populates the instance with data ga You can pass a callback that implements to in order to get notified about the completion of the operation. Note that if the underlying network stack completes the operation synchronously, the callback will be executed inline, during the call to . In this case, the property on the returned will be set to `true` to indicate that the method completed synchronously. Use the property of the to obtain the state object passed to the method. - The operation must be completed by calling the method. Typically, the method is invoked by the provided delegate. will block the calling thread until the operation is completed. + The operation must be completed by calling the method. Typically, the method is invoked by the provided delegate. will block the calling thread until the operation is completed. If you are using a connection-oriented protocol, you must first call the , , , or method, or will throw a . will ignore the `remoteEP` parameter and send data to the established in the , , , or method. @@ -4043,6 +4045,7 @@ This method populates the instance with data ga The local endpoint and the parameter are not the same address family. The has been closed. A caller higher in the call stack does not have permission for the requested operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -4082,10 +4085,10 @@ This method populates the instance with data ga This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . The parameter cannot be null. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. The socket is not in the or families. @@ -4132,10 +4135,10 @@ This method populates the instance with data ga The parameter cannot be null. The parameter cannot be empty array. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. The socket is not in the or families. @@ -4181,10 +4184,10 @@ This method populates the instance with data ga This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . The parameter cannot be null. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. The socket is not in the or families. @@ -4232,15 +4235,16 @@ This method populates the instance with data ga This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . The parameter cannot be null. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. An error occurred when attempting to access the socket. The has been closed. A caller higher in the call stack does not have permission for the requested operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -4283,16 +4287,17 @@ This method populates the instance with data ga The parameter cannot be null. The parameter cannot be empty array. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. The socket is not in the or families. An error occurred when attempting to access the socket. The has been closed. A caller higher in the call stack does not have permission for the requested operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -4427,16 +4432,17 @@ This method populates the instance with data ga This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . The parameter cannot be null. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. The socket is not in the or families. An error occurred when attempting to access the socket. The has been closed. A caller higher in the call stack does not have permission for the requested operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -4671,6 +4677,7 @@ This method populates the instance with data ga This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . The object has been closed. An error occurred when attempting to access the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -5111,7 +5118,7 @@ Duplication of the socket reference failed.
The method blocks until a connection is pending in the incoming connection queue. The method accepts the incoming connection and returns a new that can be used to send data to and receive data from the remote host. > [!NOTE] -> If you receive a , use the property to obtain the specific error code. +> If you receive a , use the property to obtain the specific error code. > [!NOTE] > This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in .NET Framework](/dotnet/framework/network-programming/network-tracing). @@ -5200,7 +5207,7 @@ Duplication of the socket reference failed.
The method blocks until a connection is pending in the incoming connection queue. The method accepts the incoming connection and returns a new that can be used to send data to and receive data from the remote host. > [!NOTE] -> If you receive a , use the property to obtain the specific error code. +> If you receive a , use the property to obtain the specific error code. > [!NOTE] > This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in .NET Framework](/dotnet/framework/network-programming/network-tracing). @@ -5289,7 +5296,7 @@ Duplication of the socket reference failed.
The method blocks until a connection is pending in the incoming connection queue. The method accepts the incoming connection and returns a new that can be used to send data to and receive data from the remote host. > [!NOTE] -> If you receive a , use the property to obtain the specific error code. +> If you receive a , use the property to obtain the specific error code. > [!NOTE] > This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in .NET Framework](/dotnet/framework/network-programming/network-tracing). @@ -8941,6 +8948,7 @@ If you're using a connectionless , To be added. The has been closed. An error occurred when attempting to access the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -8981,6 +8989,7 @@ If you're using a connectionless , To be added. The has been closed. An error occurred when attempting to access the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -9801,6 +9810,7 @@ If you're using a connectionless , An error occurred when attempting to access the socket.
The has been closed. A caller in the call stack does not have the required permissions. + The cancellation token was canceled. This exception is stored into the returned task. @@ -9846,6 +9856,7 @@ If you're using a connectionless , An error occurred when attempting to access the socket.
The has been closed. A caller in the call stack does not have the required permissions. + The cancellation token was canceled. This exception is stored into the returned task. @@ -10235,6 +10246,7 @@ You must call the Bind method before performing this operation.
is . You must call the Bind method before performing this operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -10279,6 +10291,7 @@ You must call the Bind method before performing this operation.
is . You must call the Bind method before performing this operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -11825,6 +11838,7 @@ This member outputs trace information when you enable network tracing in your ap Sends data on a connected socket. An asynchronous task that completes with the number of bytes sent. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -11865,6 +11879,7 @@ This member outputs trace information when you enable network tracing in your ap To be added. An error occurred when attempting to access the socket. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -12186,6 +12201,7 @@ This member outputs trace information when you enable network tracing in your ap The object is not connected to a remote host. The file was not found. An error occurred when attempting to access the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -12232,6 +12248,7 @@ This member outputs trace information when you enable network tracing in your ap The object is not connected to a remote host. The file was not found. An error occurred when attempting to access the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -13094,6 +13111,7 @@ This member outputs trace information when you enable network tracing in your ap is . An error occurred when attempting to access the socket. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -13138,6 +13156,7 @@ This member outputs trace information when you enable network tracing in your ap is . An error occurred when attempting to access the socket. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Sockets/SocketTaskExtensions.xml b/xml/System.Net.Sockets/SocketTaskExtensions.xml index 9c82ca78b5c..899c7b51cd5 100644 --- a/xml/System.Net.Sockets/SocketTaskExtensions.xml +++ b/xml/System.Net.Sockets/SocketTaskExtensions.xml @@ -251,6 +251,7 @@ The local endpoint and the parameter are not the same address family. The has been closed. A caller higher in the call stack does not have permission for the requested operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -304,10 +305,10 @@ To be added. The parameter cannot be null. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. An error occurred when attempting to access the socket. @@ -367,10 +368,10 @@ The parameter cannot be null. The parameter cannot be empty array. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. An error occurred when attempting to access the socket. @@ -429,10 +430,10 @@ To be added. The parameter cannot be null. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. An error occurred when attempting to access the socket. @@ -482,15 +483,16 @@ To be added. The parameter cannot be null. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. An error occurred when attempting to access the socket. The has been closed. A caller higher in the call stack does not have permission for the requested operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -536,15 +538,16 @@ The parameter cannot be null. The parameter cannot be empty array. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. An error occurred when attempting to access the socket. The has been closed. A caller higher in the call stack does not have permission for the requested operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -589,15 +592,16 @@ To be added. The parameter cannot be null. - is less than . - - -or- - + is less than . + + -or- + is greater than . The is listening. An error occurred when attempting to access the socket. The has been closed. A caller higher in the call stack does not have permission for the requested operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -751,6 +755,7 @@ To be added. The has been closed. An error occurred when attempting to access the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1023,6 +1028,7 @@ To be added. An error occurred when attempting to access the socket. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.Sockets/TcpClient.xml b/xml/System.Net.Sockets/TcpClient.xml index 150c53b66c0..7c72e1e6005 100644 --- a/xml/System.Net.Sockets/TcpClient.xml +++ b/xml/System.Net.Sockets/TcpClient.xml @@ -43,29 +43,29 @@ Provides client connections for TCP network services. - or created with the TCP must be listening for incoming connection requests. You can connect to this listener in one of the following two ways: - -- Create a `TcpClient` and call one of the three available methods. - -- Create a `TcpClient` using the host name and port number of the remote host. This constructor will automatically attempt a connection. - + or created with the TCP must be listening for incoming connection requests. You can connect to this listener in one of the following two ways: + +- Create a `TcpClient` and call one of the three available methods. + +- Create a `TcpClient` using the host name and port number of the remote host. This constructor will automatically attempt a connection. + > [!NOTE] -> If you want to send connectionless datagrams in synchronous blocking mode, use the class. - - - -## Examples - The following code example establishes a `TcpClient` connection. - +> If you want to send connectionless datagrams in synchronous blocking mode, use the class. + + + +## Examples + The following code example establishes a `TcpClient` connection. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpClient/CPP/tcpclient.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Overview/tcpclient.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpClient/VB/tcpclient.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpClient/VB/tcpclient.vb" id="Snippet1"::: + ]]> @@ -125,26 +125,26 @@ Initializes a new instance of the class. - and allows the underlying service provider to assign the most appropriate local IP address and port number. You must first call the method before sending and receiving data. - + and allows the underlying service provider to assign the most appropriate local IP address and port number. You must first call the method before sending and receiving data. + > [!NOTE] -> On .NET Framework, this constructor works only with IPv4 address types. - +> On .NET Framework, this constructor works only with IPv4 address types. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates how to use the parameterless constructor to create a new . - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates how to use the parameterless constructor to create a new . + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet4"::: + ]]> @@ -186,25 +186,25 @@ The to which you bind the TCP . Initializes a new instance of the class and binds it to the specified local endpoint. - and binds it to the specified by the `localEP` parameter. Before you call this constructor, you must create an `IPEndPoint` using the IP address and port number from which you intend to send and receive data. You do not need to specify a local IP address and port number before connecting and communicating. If you create a `TcpClient` using any other constructor, the underlying service provider will assign the most appropriate local IP address and port number. - - You must call the method before sending and receiving data. - + and binds it to the specified by the `localEP` parameter. Before you call this constructor, you must create an `IPEndPoint` using the IP address and port number from which you intend to send and receive data. You do not need to specify a local IP address and port number before connecting and communicating. If you create a `TcpClient` using any other constructor, the underlying service provider will assign the most appropriate local IP address and port number. + + You must call the method before sending and receiving data. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates how to create an instance of the class using a local endpoint. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates how to create an instance of the class using a local endpoint. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet2"::: + ]]> The parameter is . @@ -249,28 +249,28 @@ The of the IP protocol. Initializes a new instance of the class with the specified family. - [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates how to create an instance of the class. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates how to create an instance of the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet15"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet15"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet15"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet15"::: + ]]> - The parameter is not equal to AddressFamily.InterNetwork - - -or- - + The parameter is not equal to AddressFamily.InterNetwork + + -or- + The parameter is not equal to AddressFamily.InterNetworkV6 @@ -312,28 +312,28 @@ The port number of the remote host to which you intend to connect. Initializes a new instance of the class and connects to the specified port on the specified host. - and makes a synchronous connection attempt to the provided host name and port number. The underlying service provider will assign the most appropriate local IP address and port number. `TcpClient` will block until it either connects or fails. This constructor allows you to initialize, resolve the DNS host name, and connect in one convenient step. - - If IPv6 is enabled and the method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address. - + and makes a synchronous connection attempt to the provided host name and port number. The underlying service provider will assign the most appropriate local IP address and port number. `TcpClient` will block until it either connects or fails. This constructor allows you to initialize, resolve the DNS host name, and connect in one convenient step. + + If IPv6 is enabled and the method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates how to create an instance of the class using a host name and port number. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates how to create an instance of the class using a host name and port number. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet3"::: + ]]> The parameter is . @@ -391,11 +391,11 @@ if the connection has been made; otherwise, . - can use this property to determine if a connection attempt has succeeded. It does not monitor the ongoing connection state of `TcpClient`. If the remote host closes the connection, `Active` will not be updated. If you are deriving from `TcpClient` and require closer attention to the connection state, use the property of the returned by the property. - + can use this property to determine if a connection attempt has succeeded. It does not monitor the ongoing connection state of `TcpClient`. If the remote host closes the connection, `Active` will not be updated. If you are deriving from `TcpClient` and require closer attention to the connection state, use the property of the returned by the property. + ]]> @@ -438,21 +438,21 @@ Gets the amount of data that has been received from the network and is available to be read. The number of bytes of data received from the network and available to be read. - to get the data. The available data is the total amount of data queued in the network buffer for reading. If no data is queued in the network buffer, `Available` returns 0. - - If the remote host shuts down or closes the connection, `Available` may throw a . If you receive a `SocketException`, use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following code example shows the use of the `Available` property. - + to get the data. The available data is the total amount of data queued in the network buffer for reading. If no data is queued in the network buffer, `Available` returns 0. + + If the remote host shuts down or closes the connection, `Available` may throw a . If you receive a `SocketException`, use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following code example shows the use of the `Available` property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpClient1/CPP/newtcpclient.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet1"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet1"::: + ]]> An error occurred when attempting to access the socket. @@ -515,25 +515,25 @@ The `Available` property is a way to determine whether data is queued for readin Begins an asynchronous request for a remote host connection. The remote host is specified by an and a port number (). An object that references the asynchronous connection. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block until the operation completes. To block until the operation completes, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block until the operation completes. To block until the operation completes, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . - - -## Examples - The following code example creates a and connects to a remote host. - + + +## Examples + The following code example creates a and connects to a remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpClient1/CPP/newtcpclient.cpp" id="Snippet4"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet4"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet4"::: + ]]> The parameter is . @@ -589,27 +589,27 @@ The `Available` property is a way to determine whether data is queued for readin Begins an asynchronous request for a remote host connection. The remote host is specified by an array and a port number (). An object that references the asynchronous connection. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block until the operation completes. To block until the operation completes, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - - This method is typically used immediately after a call to the method, which can return multiple IP addresses for a single host. - + method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block until the operation completes. To block until the operation completes, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + + This method is typically used immediately after a call to the method, which can return multiple IP addresses for a single host. + > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . - - -## Examples - The following code example creates a and connects to a remote host. - + + +## Examples + The following code example creates a and connects to a remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpClient1/CPP/newtcpclient.cpp" id="Snippet5"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet5"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet5"::: + ]]> The parameter is . @@ -665,23 +665,23 @@ The `Available` property is a way to determine whether data is queued for readin Begins an asynchronous request for a remote host connection. The remote host is specified by a host name () and a port number (). An object that references the asynchronous connection. - method. Typically, the method is invoked by the `asyncCallback` delegate. - - This method does not block until the operation completes. To block until the operation completes, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - - - -## Examples - The following code example creates a and connects to a remote host. - + method. Typically, the method is invoked by the `asyncCallback` delegate. + + This method does not block until the operation completes. To block until the operation completes, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + + + +## Examples + The following code example creates a and connects to a remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpClient1/CPP/newtcpclient.cpp" id="Snippet6"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet6"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet6"::: + ]]> The parameter is . @@ -741,19 +741,19 @@ The `Available` property is a way to determine whether data is queued for readin Gets or sets the underlying . The underlying network . - creates a to send and receive data over a network. Classes deriving from `TcpClient` can use this property to get or set this `Socket`. Use the underlying `Socket` returned from `Client` if you require access beyond that which `TcpClient` provides. You can also use `Client` to set the underlying `Socket` to an existing `Socket`. This might be useful if you want to take advantage of the simplicity of `TcpClient` using a pre-existing `Socket`. - - - -## Examples - The following code example demonstrates the use of the `Client` property. In this example, the receive buffer size of the underlying is changed. - + creates a to send and receive data over a network. Classes deriving from `TcpClient` can use this property to get or set this `Socket`. Use the underlying `Socket` returned from `Client` if you require access beyond that which `TcpClient` provides. You can also use `Client` to set the underlying `Socket` to an existing `Socket`. This might be useful if you want to take advantage of the simplicity of `TcpClient` using a pre-existing `Socket`. + + + +## Examples + The following code example demonstrates the use of the `Client` property. In this example, the receive buffer size of the underlying is changed. + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Client/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/TcpClientProtectedMethodsAndPropertiesExample/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/TcpClientProtectedMethodsAndPropertiesExample/VB/source.vb" id="Snippet1"::: + ]]> @@ -795,24 +795,24 @@ The `Available` property is a way to determine whether data is queued for readin Disposes this instance and requests that the underlying TCP connection be closed. - close the TCP connection. Based on the property, the TCP connection may stay open for some time after the `Close` method is called when data remains to be sent. There is no notification provided when the underlying connection has completed closing. - - Calling this method will eventually result in the close of the associated `Socket` and will also close the associated that is used to send and receive data if one was created. - + close the TCP connection. Based on the property, the TCP connection may stay open for some time after the `Close` method is called when data remains to be sent. There is no notification provided when the underlying connection has completed closing. + + Calling this method will eventually result in the close of the associated `Socket` and will also close the associated that is used to send and receive data if one was created. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates closing a by calling the `Close` method. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates closing a by calling the `Close` method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/NCLTcpClientSync/CPP/tcpclient.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/ReadTimeout/tcpclient.cs" id="Snippet1"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/NetworkStream/ReadTimeout/tcpclient.cs" id="Snippet1"::: + ]]> @@ -866,28 +866,28 @@ The `Available` property is a way to determine whether data is queued for readin The to which you intend to connect. Connects the client to a remote TCP host using the specified remote network endpoint. - . Before you call `Connect`, you must create an instance of the `IPEndPoint` class using an IP address and a port number. Use this `IPEndPoint` as the `remoteEP` parameter. The `Connect` method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. - + . Before you call `Connect`, you must create an instance of the `IPEndPoint` class using an IP address and a port number. Use this `IPEndPoint` as the `remoteEP` parameter. The `Connect` method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing) - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing) + > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . - - -## Examples - The following code example uses an to connect with a remote host. - + + +## Examples + The following code example uses an to connect with a remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet7"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet7"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet7"::: + ]]> The parameter is . @@ -938,28 +938,28 @@ The `Available` property is a way to determine whether data is queued for readin The port number to which you intend to connect. Connects the client to a remote TCP host using the specified IP address and port number. - and port number. The method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. - + and port number. The method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . - - -## Examples - The following code example uses an IP Address and port number to connect with a remote host. - + + +## Examples + The following code example uses an IP Address and port number to connect with a remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet6"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet6"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet6"::: + ]]> The parameter is . @@ -1010,27 +1010,27 @@ The `Available` property is a way to determine whether data is queued for readin The port number to which you intend to connect. Connects the client to a remote TCP host using the specified IP addresses and port number. - method, which can return multiple IP addresses for a single host. Call the `Connect` method to establish a synchronous remote host connection to the host specified by the array of elements and the port number. The `Connect` method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. - + method, which can return multiple IP addresses for a single host. Call the `Connect` method to establish a synchronous remote host connection to the host specified by the array of elements and the port number. The `Connect` method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . - - -## Examples - The following code example uses an IP Address and port number to connect with a remote host. - + + +## Examples + The following code example uses an IP Address and port number to connect with a remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpClient1/CPP/newtcpclient.cpp" id="Snippet8"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet8"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet8"::: + ]]> The parameter is . @@ -1083,28 +1083,28 @@ The `Available` property is a way to determine whether data is queued for readin The port number of the remote host to which you intend to connect. Connects the client to the specified port on the specified host. - method to obtain the underlying . Use this `NetworkStream` to send and receive data. - - If IPv6 is enabled and the `Connect(String, Int32)` method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address. - + method to obtain the underlying . Use this `NetworkStream` to send and receive data. + + If IPv6 is enabled and the `Connect(String, Int32)` method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example uses the host name and port number to connect with a remote host. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example uses the host name and port number to connect with a remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet5"::: + ]]> The parameter is . @@ -1153,19 +1153,19 @@ The `Available` property is a way to determine whether data is queued for readin Connects the client to a remote TCP host using the specified endpoint as an asynchronous operation. A task representing the asynchronous operation. - object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. - - Call this method to establish a synchronous remote host connection to the specified . Before you call `Connect`, you must create an instance of the `IPEndPoint` class using an IP address and a port number. Use this `IPEndPoint` as the `remoteEP` parameter. The `Connect` method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. - + object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. + + Call this method to establish a synchronous remote host connection to the specified . Before you call `Connect`, you must create an instance of the `IPEndPoint` class using an IP address and a port number. Use this `IPEndPoint` as the `remoteEP` parameter. The `Connect` method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you've obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you've obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + > [!NOTE] > If you receive a `NotSupportedException` with the message "This protocol version is not supported" while using IPv6 address, make sure you enabled IPv6 in the constructor by passing . @@ -1216,19 +1216,19 @@ The `Available` property is a way to determine whether data is queued for readin Connects the client to a remote TCP host using the specified IP address and port number as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. - - Call this method to establish a synchronous remote host connection to the specified and port number as an asynchronous operation. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. - + object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. + + Call this method to establish a synchronous remote host connection to the specified and port number as an asynchronous operation. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . @@ -1285,19 +1285,19 @@ The `Available` property is a way to determine whether data is queued for readin Connects the client to a remote TCP host using the specified IP addresses and port number as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. - - This method is typically used immediately after a call to the method, which can return multiple IP addresses for a single host. Call this method to establish a synchronous remote host connection to the host specified by the array of elements and the port number as an asynchronous operation. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. - + object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. + + This method is typically used immediately after a call to the method, which can return multiple IP addresses for a single host. Call this method to establish a synchronous remote host connection to the host specified by the array of elements and the port number as an asynchronous operation. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . @@ -1343,19 +1343,19 @@ The `Available` property is a way to determine whether data is queued for readin Connects the client to a remote TCP host using the specified endpoint as an asynchronous operation. A task representing the asynchronous operation. - object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. - - Call this method to establish a synchronous remote host connection to the specified . Before you call `Connect`, you must create an instance of the `IPEndPoint` class using an IP address and a port number. Use this `IPEndPoint` as the `remoteEP` parameter. The `Connect` method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. - + object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. + + Call this method to establish a synchronous remote host connection to the specified . Before you call `Connect`, you must create an instance of the `IPEndPoint` class using an IP address and a port number. Use this `IPEndPoint` as the `remoteEP` parameter. The `Connect` method will block until it either connects or fails. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . @@ -1363,6 +1363,7 @@ The `Available` property is a way to determine whether data is queued for readin ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -1406,21 +1407,21 @@ The `Available` property is a way to determine whether data is queued for readin Connects the client to the specified TCP port on the specified host as an asynchronous operation. The task object representing the asynchronous operation. - object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. - - Call this method to establish a synchronous remote host connection to the specified host name and port number as an asynchronous operation. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. - - If IPv6 is enabled and the method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address. - + object will complete after the TCP connection has been established. This method does not block the calling thread while the connection request is underway. + + Call this method to establish a synchronous remote host connection to the specified host name and port number as an asynchronous operation. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. + + If IPv6 is enabled and the method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1466,19 +1467,19 @@ The `Available` property is a way to determine whether data is queued for readin Connects the client to a remote TCP host using the specified IP address and port number as an asynchronous operation. A task that represents the asynchronous connection operation. - method to obtain the underlying . Use this `NetworkStream` to send and receive data. - + method to obtain the underlying . Use this `NetworkStream` to send and receive data. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . @@ -1492,6 +1493,7 @@ The `Available` property is a way to determine whether data is queued for readin is closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1526,19 +1528,19 @@ The `Available` property is a way to determine whether data is queued for readin Connects the client to a remote TCP host using the specified IP addresses and port number as an asynchronous operation. A task that represents the asynchronous connection operation. - method, which can return multiple IP addresses for a single host. Call this method to establish a synchronous remote host connection to the host specified by the array of IP addresses and the port number as an asynchronous operation. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. - + method, which can return multiple IP addresses for a single host. Call this method to establish a synchronous remote host connection to the host specified by the array of IP addresses and the port number as an asynchronous operation. After connecting with the remote host, use the method to obtain the underlying . Use this `NetworkStream` to send and receive data. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + > [!NOTE] > If you receive NotSupportedException with message `This protocol version is not supported` while using IPv6 address, then make sure you enabled IPv6 in constructor by passing . @@ -1553,6 +1555,7 @@ The `Available` property is a way to determine whether data is queued for readin A caller higher in the call stack does not have permission for the requested operation. This method is valid for sockets that use the flag or the flag. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1587,21 +1590,21 @@ The `Available` property is a way to determine whether data is queued for readin Connects the client to the specified TCP port on the specified host as an asynchronous operation. A task that represents the asynchronous connection operation. - method to obtain the underlying . Use this `NetworkStream` to send and receive data. - - If IPv6 is enabled and the method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address. - + method to obtain the underlying . Use this `NetworkStream` to send and receive data. + + If IPv6 is enabled and the method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1613,6 +1616,7 @@ The `Available` property is a way to determine whether data is queued for readin is closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1652,21 +1656,21 @@ The `Available` property is a way to determine whether data is queued for readin if the socket was connected to a remote resource as of the most recent operation; otherwise, . - socket as of the last I/O operation. When it returns `false`, the `Client` socket was either never connected, or is no longer connected. - - Because the `Connected` property only reflects the state of the connection as of the most recent operation, you should attempt to send or receive a message to determine the current state. After the message send fails, this property no longer returns `true`. Note that this behavior is by design. You cannot reliably test the state of the connection because, in the time between the test and a send/receive, the connection could have been lost. Your code should assume the socket is connected, and gracefully handle failed transmissions. - - - -## Examples - The following code example connects to a remote endpoint and then verifies the connection. - + socket as of the last I/O operation. When it returns `false`, the `Client` socket was either never connected, or is no longer connected. + + Because the `Connected` property only reflects the state of the connection as of the most recent operation, you should attempt to send or receive a message to determine the current state. After the message send fails, this property no longer returns `true`. Note that this behavior is by design. You cannot reliably test the state of the connection because, in the time between the test and a send/receive, the connection could have been lost. Your code should assume the socket is connected, and gracefully handle failed transmissions. + + + +## Examples + The following code example connects to a remote endpoint and then verifies the connection. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpClient1/CPP/newtcpclient.cpp" id="Snippet2"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet2"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet2"::: + ]]> @@ -1751,22 +1755,22 @@ The `Available` property is a way to determine whether data is queued for readin Set to to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. It does this by invoking the `Dispose()` method of each referenced object. - + method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. It does this by invoking the `Dispose()` method of each referenced object. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + ]]> - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Overriding the Finalize Method](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ddae83kx(v=vs.100)). @@ -1809,22 +1813,22 @@ The `Available` property is a way to determine whether data is queued for readin An object returned by a call to . Ends a pending asynchronous connection attempt. - method. - + method. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following code example ends the asynchronous connection attempt. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following code example ends the asynchronous connection attempt. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpClient1/CPP/newtcpclient.cpp" id="Snippet7"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet7"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet7"::: + ]]> The parameter is . @@ -1871,21 +1875,21 @@ The `Available` property is a way to determine whether data is queued for readin if the allows only one client to use a specific port; otherwise, . The default is for Windows Server 2003 and Windows XP Service Pack 2 and later, and for all other versions. - , , , or , the client port is bound as a side effect of the method, and you cannot subsequently set the `ExclusiveAddressUse` property. - - - -## Examples - The following code example creates a and gets and sets the value of the `ExclusiveAddressUse` property. - + + + +## Examples + The following code example creates a and gets and sets the value of the `ExclusiveAddressUse` property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpClient1/CPP/newtcpclient.cpp" id="Snippet3"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet3"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/Available/newtcpclient.cs" id="Snippet3"::: + ]]> An error occurred when attempting to access the underlying socket. @@ -1929,15 +1933,15 @@ The `Available` property is a way to determine whether data is queued for readin Frees resources used by the class. - . Application code should not call this method; an object's `Finalize` method is automatically invoked during garbage collection, unless finalization by the garbage collector has been disabled by a call to the method. - - The class finalizer closes the TCP connection and releases all managed resources associated with the `TcpClient`. These resources include the underlying used for connecting with the remote host, and the used to send and receive data. The finalizer does not release any unmanaged resources. - - For more information, see [Finalize Methods and Destructors](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/0s71x931(v%3dvs.100)), [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged), and [Overriding the Finalize Method](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ddae83kx(v=vs.100)). - + . Application code should not call this method; an object's `Finalize` method is automatically invoked during garbage collection, unless finalization by the garbage collector has been disabled by a call to the method. + + The class finalizer closes the TCP connection and releases all managed resources associated with the `TcpClient`. These resources include the underlying used for connecting with the remote host, and the used to send and receive data. The finalizer does not release any unmanaged resources. + + For more information, see [Finalize Methods and Destructors](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/0s71x931(v%3dvs.100)), [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged), and [Overriding the Finalize Method](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ddae83kx(v=vs.100)). + ]]> @@ -1982,28 +1986,28 @@ The `Available` property is a way to determine whether data is queued for readin Returns the used to send and receive data. The underlying . - that you can use to send and receive data. The `NetworkStream` class inherits from the class, which provides a rich collection of methods and properties used to facilitate network communications. - - You must call the method first, or the method will throw an . After you have obtained the `NetworkStream`, call the method to send data to the remote host. Call the method to receive data arriving from the remote host. Both of these methods block until the specified operation is performed. You can avoid blocking on a read operation by checking the property. A `true` value means that data has arrived from the remote host and is available for reading. In this case, is guaranteed to complete immediately. If the remote host has shutdown its connection, will immediately return with zero bytes. - + that you can use to send and receive data. The `NetworkStream` class inherits from the class, which provides a rich collection of methods and properties used to facilitate network communications. + + You must call the method first, or the method will throw an . After you have obtained the `NetworkStream`, call the method to send data to the remote host. Call the method to receive data arriving from the remote host. Both of these methods block until the specified operation is performed. You can avoid blocking on a read operation by checking the property. A `true` value means that data has arrived from the remote host and is available for reading. In this case, is guaranteed to complete immediately. If the remote host has shutdown its connection, will immediately return with zero bytes. + > [!NOTE] -> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example uses `GetStream` to obtain the underlying . After obtaining the , it sends and receives using its and methods. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example uses `GetStream` to obtain the underlying . After obtaining the , it sends and receives using its and methods. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet14"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet14"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet14"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet14"::: + ]]> The is not connected to a remote host. @@ -2054,36 +2058,36 @@ The `GetStream` method returns a that yo Gets or sets information about the linger state of the associated socket. A . By default, lingering is disabled. - method behaves. This property when set modifies the conditions under which the connection can be reset by Winsock. Connection resets can still occur based on the IP protocol behavior. - - This property controls the length of time that the TCP connection will remain open after a call to when data remains to be sent. When you call the method, data is placed in the outgoing network buffer. This property can be used to ensure that this data is sent to the remote host before the method drops the connection. - - To enable lingering, create a instance containing the desired values, and set the `LingerState` property to this instance. - - The following table describes the behavior of the method for the possible values of the property and the property stored in the `LingerState` property. - -|LingerState.Enabled|LingerState.LingerTime|Behavior| -|-------------------------|----------------------------|--------------| -|`false` (disabled), the default value|The time-out is not applicable, (default).|Attempts to send pending data until the default IP protocol time-out expires.| -|`true` (enabled)|A nonzero time-out|Attempts to send pending data until the specified time-out expires, and if the attempt fails, then Winsock resets the connection.| -|`true` (enabled)|A zero timeout.|Discards any pending data and Winsock resets the connection.| - - The IP stack computes the default IP protocol time-out period to use based on the round trip time of the connection. In most cases, the time-out computed by the stack is more relevant than one defined by an application. This is the default behavior for a socket when the `LingerState` property is not set. - - When the property stored in the `LingerState` property is set greater than the default IP protocol time-out, the default IP protocol time-out will still apply and override. - - - -## Examples - The following code example sets and gets the sockets linger time. - + method behaves. This property when set modifies the conditions under which the connection can be reset by Winsock. Connection resets can still occur based on the IP protocol behavior. + + This property controls the length of time that the TCP connection will remain open after a call to when data remains to be sent. When you call the method, data is placed in the outgoing network buffer. This property can be used to ensure that this data is sent to the remote host before the method drops the connection. + + To enable lingering, create a instance containing the desired values, and set the `LingerState` property to this instance. + + The following table describes the behavior of the method for the possible values of the property and the property stored in the `LingerState` property. + +|LingerState.Enabled|LingerState.LingerTime|Behavior| +|-------------------------|----------------------------|--------------| +|`false` (disabled), the default value|The time-out is not applicable, (default).|Attempts to send pending data until the default IP protocol time-out expires.| +|`true` (enabled)|A nonzero time-out|Attempts to send pending data until the specified time-out expires, and if the attempt fails, then Winsock resets the connection.| +|`true` (enabled)|A zero timeout.|Discards any pending data and Winsock resets the connection.| + + The IP stack computes the default IP protocol time-out period to use based on the round trip time of the connection. In most cases, the time-out computed by the stack is more relevant than one defined by an application. This is the default behavior for a socket when the `LingerState` property is not set. + + When the property stored in the `LingerState` property is set greater than the default IP protocol time-out, the default IP protocol time-out will still apply and override. + + + +## Examples + The following code example sets and gets the sockets linger time. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet12"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet12"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet12"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet12"::: + ]]> @@ -2129,20 +2133,20 @@ The `GetStream` method returns a that yo if the delay is disabled; otherwise, . The default value is . - does not send a packet over the network until it has collected a significant amount of outgoing data. Because of the amount of overhead in a TCP segment, sending small amounts of data is inefficient. However, situations do exist where you need to send very small amounts of data or expect immediate responses from each packet you send. Your decision should weigh the relative importance of network efficiency versus application requirements. - - - -## Examples - The following code example disables the delay. It then checks the value of `NoDelay` to verify that the property was successfully set. - + does not send a packet over the network until it has collected a significant amount of outgoing data. Because of the amount of overhead in a TCP segment, sending small amounts of data is inefficient. However, situations do exist where you need to send very small amounts of data or expect immediate responses from each packet you send. Your decision should weigh the relative importance of network efficiency versus application requirements. + + + +## Examples + The following code example disables the delay. It then checks the value of `NoDelay` to verify that the property was successfully set. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet13"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet13"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet13"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet13"::: + ]]> @@ -2190,30 +2194,30 @@ The `GetStream` method returns a that yo Gets or sets the size of the receive buffer. The size of the receive buffer, in bytes. The default value is 8192 bytes. - method. Use the property to set this size. If your application will be receiving bulk data, you should pass the `Read` method a very large application buffer. - - If the network buffer is smaller than the amount of data you request in the `Read` method, you will not be able to retrieve the desired amount of data in one read operation. This incurs the overhead of additional calls to the `Read` method. - - - -## Examples - The following code example sets and gets the receive buffer size. - + method. Use the property to set this size. If your application will be receiving bulk data, you should pass the `Read` method a very large application buffer. + + If the network buffer is smaller than the amount of data you request in the `Read` method, you will not be able to retrieve the desired amount of data in one read operation. This incurs the overhead of additional calls to the `Read` method. + + + +## Examples + The following code example sets and gets the receive buffer size. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet8"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet8"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet8"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet8"::: + ]]> - An error occurred when setting the buffer size. - - -or- - + An error occurred when setting the buffer size. + + -or- + In .NET Compact Framework applications, you cannot set this property. For a workaround, see the Platform Note in Remarks. @@ -2262,20 +2266,20 @@ The `GetStream` method returns a that yo Gets or sets the amount of time a will wait to receive data once a read operation is initiated. The time-out value of the connection in milliseconds. The default value is 0. - method will block until it is able to receive data. This time is measured in milliseconds. If the time-out expires before `Read` successfully completes, throws a . There is no time-out by default. - - - -## Examples - The following code example sets and gets the receive time out. - + method will block until it is able to receive data. This time is measured in milliseconds. If the time-out expires before `Read` successfully completes, throws a . There is no time-out by default. + + + +## Examples + The following code example sets and gets the receive time out. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet10"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet10"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet10"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet10"::: + ]]> @@ -2325,24 +2329,24 @@ The `GetStream` method returns a that yo Gets or sets the size of the send buffer. The size of the send buffer, in bytes. The default value is 8192 bytes. - method. This property actually manipulates the network buffer space allocated for send operation. - - Your network buffer should be at least as large as your application buffer to ensure that the desired data will be stored and sent in one operation. Use the property to set this size. If your application will be sending bulk data, you should pass the `Write` method a very large application buffer. - - If the network buffer is smaller than the amount of data you provide the `Write` method, several network send operations will be performed for every call you make to the `Write` method. You can achieve greater data throughput by ensuring that your network buffer is at least as large as your application buffer. - - - -## Examples - The following code example sets and gets the send buffer size. - + method. This property actually manipulates the network buffer space allocated for send operation. + + Your network buffer should be at least as large as your application buffer to ensure that the desired data will be stored and sent in one operation. Use the property to set this size. If your application will be sending bulk data, you should pass the `Write` method a very large application buffer. + + If the network buffer is smaller than the amount of data you provide the `Write` method, several network send operations will be performed for every call you make to the `Write` method. You can achieve greater data throughput by ensuring that your network buffer is at least as large as your application buffer. + + + +## Examples + The following code example sets and gets the send buffer size. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet9"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet9"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet9"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet9"::: + ]]> @@ -2392,22 +2396,22 @@ The `GetStream` method returns a that yo Gets or sets the amount of time a will wait for a send operation to complete successfully. The send time-out value, in milliseconds. The default is 0. - method will block until it is able to return successfully. This time is measured in milliseconds. - - After you call the method, the underlying returns the number of bytes actually sent to the host. The `SendTimeout` property determines the amount of time a will wait before receiving the number of bytes returned. If the time-out expires before the `Send` method successfully completes, `TcpClient` will throw a . There is no time-out by default. - - - -## Examples - The following code example sets and gets the `SendTimeout` value. - + method will block until it is able to return successfully. This time is measured in milliseconds. + + After you call the method, the underlying returns the number of bytes actually sent to the host. The `SendTimeout` property determines the amount of time a will wait before receiving the number of bytes returned. If the time-out expires before the `Send` method successfully completes, `TcpClient` will throw a . There is no time-out by default. + + + +## Examples + The following code example sets and gets the `SendTimeout` value. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet11"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/source.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet11"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/ClassicTcpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet11"::: + ]]> @@ -2452,10 +2456,10 @@ The `GetStream` method returns a that yo . The IDisposable.Dispose method leaves the in an unusable state. After calling IDisposable.Dispose, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). -> [!NOTE] +> [!NOTE] > Always call IDisposable.Dispose before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's **Finalize** method. ]]> diff --git a/xml/System.Net.Sockets/TcpListener.xml b/xml/System.Net.Sockets/TcpListener.xml index d42bfcfe459..ab5c457d231 100644 --- a/xml/System.Net.Sockets/TcpListener.xml +++ b/xml/System.Net.Sockets/TcpListener.xml @@ -39,29 +39,29 @@ Listens for connections from TCP network clients. - class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode. You can use either a or a to connect with a . Create a using an , a Local IP address and port number, or just a port number. Specify for the local IP address and 0 for the local port number if you want the underlying service provider to assign those values for you. If you choose to do this, you can use the property to identify the assigned information, after the socket has connected. - - Use the method to begin listening for incoming connection requests. will queue incoming connections until you either call the method or it has queued . Use either or to pull a connection from the incoming connection request queue. These two methods will block. If you want to avoid blocking, you can use the method first to determine if connection requests are available in the queue. - - Call the method to close the . - + class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode. You can use either a or a to connect with a . Create a using an , a Local IP address and port number, or just a port number. Specify for the local IP address and 0 for the local port number if you want the underlying service provider to assign those values for you. If you choose to do this, you can use the property to identify the assigned information, after the socket has connected. + + Use the method to begin listening for incoming connection requests. will queue incoming connections until you either call the method or it has queued . Use either or to pull a connection from the incoming connection request queue. These two methods will block. If you want to avoid blocking, you can use the method first to determine if connection requests are available in the queue. + + Call the method to close the . + > [!NOTE] -> The method does not close any accepted connections. You are responsible for closing these separately. - - - -## Examples - The following code example creates a . - +> The method does not close any accepted connections. You are responsible for closing these separately. + + + +## Examples + The following code example creates a . + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpListener/CPP/tcpserver.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/Overview/tcpserver.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener/VB/tcpserver.vb" id="Snippet1"::: - - See for a client example. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener/VB/tcpserver.vb" id="Snippet1"::: + + See for a client example. + ]]> @@ -135,24 +135,24 @@ The port on which to listen for incoming connection attempts. Initializes a new instance of the class that listens on the specified port. - or constructors. - - This constructor allows you to specify the port number on which to listen for incoming connection attempts. With this constructor, the underlying service provider assigns the most appropriate network address. If you do not care which local port is used, you can specify 0 for the port number. In this case, the service provider will assign an available ephemeral port number. If you use this approach, you can discover what local network address and port number has been assigned by using the property. - - Call the method to begin listening for incoming connection attempts. - - - -## Examples - The following code example creates a using a local port number. - + or constructors. + + This constructor allows you to specify the port number on which to listen for incoming connection attempts. With this constructor, the underlying service provider assigns the most appropriate network address. If you do not care which local port is used, you can specify 0 for the port number. In this case, the service provider will assign an available ephemeral port number. If you use this approach, you can discover what local network address and port number has been assigned by using the property. + + Call the method to begin listening for incoming connection attempts. + + + +## Examples + The following code example creates a using a local port number. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/.ctor/source.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet3"::: + ]]> @@ -197,27 +197,27 @@ An that represents the local endpoint to which to bind the listener . Initializes a new instance of the class with the specified local endpoint. - using the desired local IP address and port number. Pass this to the constructor as the `localEP` parameter. - - If you do not care which local address is assigned, you can create an using as the address parameter, and the underlying service provider will assign the most appropriate network address. This might help simplify your application if you have multiple network interfaces. If you do not care which local port is used, you can create an using 0 for the port number. In this case, the service provider will assign an available ephemeral port number. If you use this approach, you can discover what local network address and port number has been assigned by using the property. - - Call the method to begin listening for incoming connection attempts. - + using the desired local IP address and port number. Pass this to the constructor as the `localEP` parameter. + + If you do not care which local address is assigned, you can create an using as the address parameter, and the underlying service provider will assign the most appropriate network address. This might help simplify your application if you have multiple network interfaces. If you do not care which local port is used, you can create an using 0 for the port number. In this case, the service provider will assign an available ephemeral port number. If you use this approach, you can discover what local network address and port number has been assigned by using the property. + + Call the method to begin listening for incoming connection attempts. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example creates an instance of the class using the local endpoint. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example creates an instance of the class using the local endpoint. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/.ctor/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet1"::: + ]]> @@ -265,25 +265,25 @@ The port on which to listen for incoming connection attempts. Initializes a new instance of the class that listens for incoming connection attempts on the specified local IP address and port number. - using the desired local address. Pass this to the constructor as the `localaddr` parameter. If you do not care which local address is assigned, specify for the `localaddr` parameter, and the underlying service provider will assign the most appropriate network address. This might help simplify your application if you have multiple network interfaces. If you do not care which local port is used, you can specify 0 for the port number. In this case, the service provider will assign an available port number between 1024 and 65535. If you use this approach, you can discover what local network address and port number has been assigned by using the property. - - Call the method to begin listening for incoming connection attempts. - + using the desired local address. Pass this to the constructor as the `localaddr` parameter. If you do not care which local address is assigned, specify for the `localaddr` parameter, and the underlying service provider will assign the most appropriate network address. This might help simplify your application if you have multiple network interfaces. If you do not care which local port is used, you can specify 0 for the port number. In this case, the service provider will assign an available port number between 1024 and 65535. If you use this approach, you can discover what local network address and port number has been assigned by using the property. + + Call the method to begin listening for incoming connection attempts. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example creates an instance of the class using a local IP address and port number. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example creates an instance of the class using a local IP address and port number. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/.ctor/source.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet2"::: + ]]> @@ -331,25 +331,25 @@ Accepts a pending connection request. A used to send and receive data. - is a blocking method that returns a that you can use to send and receive data. If you want to avoid blocking, use the method to determine if connection requests are available in the incoming connection queue. - - The returned is initialized with the IP address and port number of the remote host. You can use any of the and methods available in the class to communicate with the remote host. When you are finished using the , be sure to call its method. If your application is relatively simple, consider using the method rather than the method. provides you with simple methods for sending and receiving data over a network in blocking synchronous mode. - + is a blocking method that returns a that you can use to send and receive data. If you want to avoid blocking, use the method to determine if connection requests are available in the incoming connection queue. + + The returned is initialized with the IP address and port number of the remote host. You can use any of the and methods available in the class to communicate with the remote host. When you are finished using the , be sure to call its method. If your application is relatively simple, consider using the method rather than the method. provides you with simple methods for sending and receiving data over a network in blocking synchronous mode. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - In the following code example, the method is used to return a . This is used to communicate with the newly connected client. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + In the following code example, the method is used to return a . This is used to communicate with the newly connected client. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/.ctor/source.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListener.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet4"::: + ]]> The listener has not been started with a call to . @@ -394,16 +394,16 @@ Accepts a pending connection request as an asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns a used to send and receive data. - object will complete after the socket connection has been accepted. - - The returned in is initialized with the IP address and port number of the remote host. You can use any of the and methods available in the class to communicate with the remote host. When you are finished using the , be sure to call its method. If your application is relatively simple, consider using the method rather than the method. provides you with simple methods for sending and receiving data over a network in blocking synchronous mode. - + object will complete after the socket connection has been accepted. + + The returned in is initialized with the IP address and port number of the remote host. You can use any of the and methods available in the class to communicate with the remote host. When you are finished using the , be sure to call its method. If your application is relatively simple, consider using the method rather than the method. provides you with simple methods for sending and receiving data over a network in blocking synchronous mode. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -441,20 +441,21 @@ Accepts a pending connection request as a cancellable asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns a used to send and receive data. - object will complete after the socket connection has been accepted. - - The returned in is initialized with the IP address and port number of the remote host. You can use any of the and methods available in the class to communicate with the remote host. When you are finished using the , be sure to call its method. If your application is relatively simple, consider using the method rather than the method. provides you with simple methods for sending and receiving data over a network in blocking synchronous mode. - + object will complete after the socket connection has been accepted. + + The returned in is initialized with the IP address and port number of the remote host. You can use any of the and methods available in the class to communicate with the remote host. When you are finished using the , be sure to call its method. If your application is relatively simple, consider using the method rather than the method. provides you with simple methods for sending and receiving data over a network in blocking synchronous mode. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -494,25 +495,25 @@ Accepts a pending connection request. A used to send and receive data. - is a blocking method that returns a that you can use to send and receive data. Use the method to determine if connection requests are available in the incoming connection queue if you want to avoid blocking. - - Use the method to obtain the underlying of the returned . The will provide you with methods for sending and receiving with the remote host. When you are through with the , be sure to call its method. If you want greater flexibility than a offers, consider using . - + is a blocking method that returns a that you can use to send and receive data. Use the method to determine if connection requests are available in the incoming connection queue if you want to avoid blocking. + + Use the method to obtain the underlying of the returned . The will provide you with methods for sending and receiving with the remote host. When you are through with the , be sure to call its method. If you want greater flexibility than a offers, consider using . + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - In the following code example, the method is used to return a . This is used to communicate with the newly connected client. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + In the following code example, the method is used to return a . This is used to communicate with the newly connected client. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic TcpListenerExample/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/AcceptTcpClient/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListenerExample/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic TcpListenerExample/VB/source.vb" id="Snippet1"::: + ]]> The listener has not been started with a call to . @@ -559,16 +560,16 @@ Accepts a pending connection request as an asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns a used to send and receive data. - object will complete after the TCP connection has been accepted. - - Use the method to obtain the underlying of the returned in the . The will provide you with methods for sending and receiving with the remote host. When you are through with the , be sure to call its method. If you want greater flexibility than a offers, consider using or . - + object will complete after the TCP connection has been accepted. + + Use the method to obtain the underlying of the returned in the . The will provide you with methods for sending and receiving with the remote host. When you are through with the , be sure to call its method. If you want greater flexibility than a offers, consider using or . + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -608,20 +609,21 @@ Accepts a pending connection request as a cancellable asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns a used to send and receive data. - object will complete after the TCP connection has been accepted. - - Use the method to obtain the underlying of the returned in the . The will provide you with methods for sending and receiving with the remote host. When you are through with the , be sure to call its method. If you want greater flexibility than a offers, consider using or . - + object will complete after the TCP connection has been accepted. + + Use the method to obtain the underlying of the returned in the . The will provide you with methods for sending and receiving with the remote host. When you are through with the , be sure to call its method. If you want greater flexibility than a offers, consider using or . + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -668,11 +670,11 @@ if is actively listening; otherwise, . - can use this property to determine if the is currently listening for incoming connection attempts. The property can be used to avoid redundant attempts. - + can use this property to determine if the is currently listening for incoming connection attempts. The property can be used to avoid redundant attempts. + ]]> @@ -721,19 +723,19 @@ A Boolean value that specifies whether to enable or disable NAT traversal. Enables or disables Network Address Translation (NAT) traversal on a instance. - method is used to enable or disable NAT traversal for a instance. NAT traversal may be provided using Teredo, 6to4, or an ISATAP tunnel. - - When the `allowed` parameter is false, the option on the associated socket is set to . This explicitly disables NAT traversal for a instance. - - When the `allowed` parameter is true, the option on the associated socket is set to . This may allow NAT traversal for a depending on firewall rules in place on the system. - - The method must be invoked prior to calling the method to begin listening for incoming connection requests (before the socket is bound). If method is called after the method, then an will be thrown. - - A Teredo address is an IPv6 address with the prefix of 2001::/32. Teredo addresses can be returned through normal DNS name resolution or enumerated as an IPv6 address assigned to a local interface. - + method is used to enable or disable NAT traversal for a instance. NAT traversal may be provided using Teredo, 6to4, or an ISATAP tunnel. + + When the `allowed` parameter is false, the option on the associated socket is set to . This explicitly disables NAT traversal for a instance. + + When the `allowed` parameter is true, the option on the associated socket is set to . This may allow NAT traversal for a depending on firewall rules in place on the system. + + The method must be invoked prior to calling the method to begin listening for incoming connection requests (before the socket is bound). If method is called after the method, then an will be thrown. + + A Teredo address is an IPv6 address with the prefix of 2001::/32. Teredo addresses can be returned through normal DNS name resolution or enumerated as an IPv6 address assigned to a local interface. + ]]> The method was called after calling the method @@ -786,33 +788,33 @@ Begins an asynchronous operation to accept an incoming connection attempt. An that references the asynchronous creation of the . - operation must be completed by calling the method. Typically, the method is invoked by the `callback` delegate. - - This method does not block until the operation completes. To block until the operation completes, use the method. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - + operation must be completed by calling the method. Typically, the method is invoked by the `callback` delegate. + + This method does not block until the operation completes. To block until the operation completes, use the method. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + > [!NOTE] -> You can call the property of the returned to identify the remote host's network address and port number. - +> You can call the property of the returned to identify the remote host's network address and port number. + > [!NOTE] -> If you receive a , use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates the use of the method to create and connect a socket. The callback delegate calls the method to end the asynchronous request. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates the use of the method to create and connect a socket. The callback delegate calls the method to end the asynchronous request. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/cpp/tcpserver.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/BeginAcceptSocket/tcpserver.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet4"::: + ]]> An error occurred while attempting to access the socket. @@ -861,30 +863,30 @@ Begins an asynchronous operation to accept an incoming connection attempt. An that references the asynchronous creation of the . - operation must be completed by calling the method. Typically, the method is invoked by the `callback` delegate. - - This method does not block until the operation completes. To block until the operation completes, use the method. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - + operation must be completed by calling the method. Typically, the method is invoked by the `callback` delegate. + + This method does not block until the operation completes. To block until the operation completes, use the method. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + > [!NOTE] -> If you receive a , use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates the use of the method to create and connect a socket. The callback delegate calls the method to end the asynchronous request. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates the use of the method to create and connect a socket. The callback delegate calls the method to end the asynchronous request. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/cpp/tcpserver.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/BeginAcceptSocket/tcpserver.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet5"::: + ]]> An error occurred while attempting to access the socket. @@ -968,33 +970,33 @@ An returned by a call to the method. Asynchronously accepts an incoming connection attempt and creates a new to handle remote host communication. - A . - + A . + The used to send and receive data. - method. - + method. + > [!NOTE] -> You can call the property of the returned to identify the remote host's network address and port number. - +> You can call the property of the returned to identify the remote host's network address and port number. + > [!NOTE] -> If you receive a , use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates the use of the method to create and connect a socket. The callback delegate calls the method to end the asynchronous request. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates the use of the method to create and connect a socket. The callback delegate calls the method to end the asynchronous request. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/cpp/tcpserver.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/BeginAcceptSocket/tcpserver.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet4"::: + ]]> The underlying has been closed. @@ -1041,33 +1043,33 @@ An returned by a call to the method. Asynchronously accepts an incoming connection attempt and creates a new to handle remote host communication. - A . - + A . + The used to send and receive data. - method. - + method. + > [!NOTE] -> You can call the property of the underlying socket () to identify the remote host's network address and port number. - +> You can call the property of the underlying socket () to identify the remote host's network address and port number. + > [!NOTE] -> If you receive a , use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> If you receive a , use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates the use of the method to create and connect a socket. The callback delegate calls the method to end the asynchronous request. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates the use of the method to create and connect a socket. The callback delegate calls the method to end the asynchronous request. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/cpp/tcpserver.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/BeginAcceptSocket/tcpserver.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet5"::: + ]]> @@ -1109,22 +1111,22 @@ if the allows only one to listen to a specific port; otherwise, . The default is for Windows Server 2003 and Windows XP Service Pack 2 and later, and for all other versions. - property to prevent multiple listeners from listening to a specific port. - - Set this property before calling , or call the method and then set this property. - - - -## Examples - The following code example gets and sets the property. - + property to prevent multiple listeners from listening to a specific port. + + Set this property before calling , or call the method and then set this property. + + + +## Examples + The following code example gets and sets the property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/cpp/tcpserver.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/BeginAcceptSocket/tcpserver.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet2"::: + ]]> The has been started. Call the method and then set the property. @@ -1161,7 +1163,7 @@ class finalizer free resources associated with the instance. ]]> @@ -1205,20 +1207,20 @@ The class finalizer free resources associa Gets the underlying of the current . The to which the is bound. - property to identify the local network interface and port number being used to listen for incoming client connection requests, after a socket connection has been made. You must first cast this to an . You can then call the property to retrieve the local IP address, and the property to retrieve the local port number. - - - -## Examples - The following code example displays the local IP address and port number on which the is listening for incoming connection requests. - + property to identify the local network interface and port number being used to listen for incoming client connection requests, after a socket connection has been made. You must first cast this to an . You can then call the property to retrieve the local IP address, and the property to retrieve the local port number. + + + +## Examples + The following code example displays the local IP address and port number on which the is listening for incoming connection requests. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/TcpListener_Pending_LocalEndPoint/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/LocalEndpoint/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/TcpListener_Pending_LocalEndPoint/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/TcpListener_Pending_LocalEndPoint/VB/source.vb" id="Snippet1"::: + ]]> @@ -1264,20 +1266,20 @@ The class finalizer free resources associa if connections are pending; otherwise, . - and methods block execution until the method has queued an incoming connection request, the method can be used to determine if connections are available before attempting to accept them. - - - -## Examples - The following code example checks the method. If a connection request is waiting to be accepted, then a call to the method is made. - + and methods block execution until the method has queued an incoming connection request, the method can be used to determine if connections are available before attempting to accept them. + + + +## Examples + The following code example checks the method. If a connection request is waiting to be accepted, then a call to the method is made. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/TcpListener_Pending_LocalEndPoint/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/LocalEndpoint/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/TcpListener_Pending_LocalEndPoint/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/TcpListener_Pending_LocalEndPoint/VB/source.vb" id="Snippet1"::: + ]]> The listener has not been started with a call to . @@ -1332,22 +1334,22 @@ The class finalizer free resources associa Gets the underlying network . The underlying . - creates a to listen for incoming client connection requests. Classes deriving from can use this property to get this . Use the underlying returned by the property if you require access beyond that which provides. - + creates a to listen for incoming client connection requests. Classes deriving from can use this property to get this . Use the underlying returned by the property if you require access beyond that which provides. + > [!NOTE] -> The property only returns the used to listen for incoming client connection requests. Use the method to accept a pending connection request and obtain a for sending and receiving data. You can also use the method to accept a pending connection request and obtain a for sending and receiving data. - - - -## Examples - The following code example demonstrates the use of the property. The underlying is retrieved and the option is configured to time out after 10 seconds if data still remains in the network buffer after the connection is closed. - +> The property only returns the used to listen for incoming client connection requests. Use the method to accept a pending connection request and obtain a for sending and receiving data. You can also use the method to accept a pending connection request and obtain a for sending and receiving data. + + + +## Examples + The following code example demonstrates the use of the property. The underlying is retrieved and the option is configured to time out after 10 seconds if data still remains in the network buffer after the connection is closed. + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/Server/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/TcpListenerProtectedMembers1/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/TcpListenerProtectedMembers1/VB/source.vb" id="Snippet1"::: + ]]> @@ -1408,27 +1410,27 @@ The class finalizer free resources associa Starts listening for incoming connection requests. - method initializes the underlying , binds it to a local endpoint, and listens for incoming connection attempts. If a connection request is received, the method will queue the request and continue listening for additional requests until you call the method. If receives a connection request after it has already queued the maximum number of connections, it will throw a on the client. - - To remove a connection from the incoming connection queue, use either the method or the method. The method will remove a connection from the queue and return a that you can use to send and receive data. The method will return a that you can use to do the same. If your application only requires synchronous I/O, use . For more detailed behavioral control, use . Both of these methods block until a connection request is available in the queue. - - Use the method to close the and stop listening. You are responsible for closing your accepted connections separately. - + method initializes the underlying , binds it to a local endpoint, and listens for incoming connection attempts. If a connection request is received, the method will queue the request and continue listening for additional requests until you call the method. If receives a connection request after it has already queued the maximum number of connections, it will throw a on the client. + + To remove a connection from the incoming connection queue, use either the method or the method. The method will remove a connection from the queue and return a that you can use to send and receive data. The method will return a that you can use to do the same. If your application only requires synchronous I/O, use . For more detailed behavioral control, use . Both of these methods block until a connection request is available in the queue. + + Use the method to close the and stop listening. You are responsible for closing your accepted connections separately. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates how is used to listen for incoming client connection attempts. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates how is used to listen for incoming client connection attempts. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/cpp/tcpserver.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/BeginAcceptSocket/tcpserver.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet3"::: + ]]> Use the property to obtain the specific error code. When you have obtained this code, you can refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error. @@ -1477,30 +1479,30 @@ The class finalizer free resources associa The maximum length of the pending connections queue. Starts listening for incoming connection requests with a maximum number of pending connection. - method initializes the underlying , binds it to a local endpoint, and listens for incoming connection attempts. If a connection request is received, will queue the request and continue listening for additional requests until you call the method. If receives a connection request after it has already queued the maximum number of connections it will throw a on the client. - - To remove a connection from the incoming connection queue, use either the method or the method. The method will remove a connection from the queue and return a that you can use to send and receive data. The method will return a that you can use to do the same. If your application only requires synchronous I/O, use the . For more detailed behavioral control, use method. Both of these methods block until a connection request is available in the queue. - - Use the method to close the and stop listening. You are responsible for closing your accepted connections separately. - + method initializes the underlying , binds it to a local endpoint, and listens for incoming connection attempts. If a connection request is received, will queue the request and continue listening for additional requests until you call the method. If receives a connection request after it has already queued the maximum number of connections it will throw a on the client. + + To remove a connection from the incoming connection queue, use either the method or the method. The method will remove a connection from the queue and return a that you can use to send and receive data. The method will return a that you can use to do the same. If your application only requires synchronous I/O, use the . For more detailed behavioral control, use method. Both of these methods block until a connection request is available in the queue. + + Use the method to close the and stop listening. You are responsible for closing your accepted connections separately. + > [!NOTE] -> Use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> Use the property to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates how is used to listen for incoming client connection attempts. - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates how is used to listen for incoming client connection attempts. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/cpp/tcpserver.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/BeginAcceptSocket/tcpserver.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener1/VB/tcpserver.vb" id="Snippet3"::: + ]]> An error occurred while accessing the socket. @@ -1550,23 +1552,23 @@ The class finalizer free resources associa Closes the listener. - closes the listener. Any unaccepted connection requests in the queue will be lost. Remote hosts waiting for a connection to be accepted will throw a . You are responsible for closing your accepted connections separately. - + closes the listener. Any unaccepted connection requests in the queue will be lost. Remote hosts waiting for a connection to be accepted will throw a . You are responsible for closing your accepted connections separately. + > [!NOTE] -> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example demonstrates using the method to close the underlying . - +> This member outputs trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example demonstrates using the method to close the underlying . + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.TcpListener/CPP/tcpserver.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/TcpListener/Overview/tcpserver.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener/VB/tcpserver.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.TcpListener/VB/tcpserver.vb" id="Snippet1"::: + ]]> Use the property to obtain the specific error code. When you have obtained this code, you can refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error. diff --git a/xml/System.Net.Sockets/UdpClient.xml b/xml/System.Net.Sockets/UdpClient.xml index 4a9ebe9c1ce..ddfba70b2d3 100644 --- a/xml/System.Net.Sockets/UdpClient.xml +++ b/xml/System.Net.Sockets/UdpClient.xml @@ -43,31 +43,31 @@ Provides User Datagram Protocol (UDP) network services. - class provides simple methods for sending and receiving connectionless UDP datagrams in blocking synchronous mode. Because UDP is a connectionless transport protocol, you do not need to establish a remote host connection prior to sending and receiving data. You do, however, have the option of establishing a default remote host in one of the following two ways: - -- Create an instance of the class using the remote host name and port number as parameters. - -- Create an instance of the class and then call the method. - - You can use any of the send methods provided in the to send data to a remote device. Use the method to receive data from remote hosts. - + class provides simple methods for sending and receiving connectionless UDP datagrams in blocking synchronous mode. Because UDP is a connectionless transport protocol, you do not need to establish a remote host connection prior to sending and receiving data. You do, however, have the option of establishing a default remote host in one of the following two ways: + +- Create an instance of the class using the remote host name and port number as parameters. + +- Create an instance of the class and then call the method. + + You can use any of the send methods provided in the to send data to a remote device. Use the method to receive data from remote hosts. + > [!NOTE] -> Do not call using a host name or if you have already specified a default remote host. If you do, will throw an exception. - - methods also allow you to send and receive multicast datagrams. Use the method to subscribe a to a multicast group. Use the method to unsubscribe a from a multicast group. - - - -## Examples - The following example establishes a connection using the host name `www.contoso.com` on port 11000. A small string message is sent to two separate remote host machines. The method blocks execution until a message is received. Using the passed to , the identity of the responding host is revealed. - +> Do not call using a host name or if you have already specified a default remote host. If you do, will throw an exception. + + methods also allow you to send and receive multicast datagrams. Use the method to subscribe a to a multicast group. Use the method to unsubscribe a from a multicast group. + + + +## Examples + The following example establishes a connection using the host name `www.contoso.com` on port 11000. A small string message is sent to two separate remote host machines. The method blocks execution until a message is received. Using the passed to , the identity of the responding host is revealed. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClientExample/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Overview/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClientExample/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClientExample/VB/source.vb" id="Snippet1"::: + ]]> @@ -123,25 +123,25 @@ Initializes a new instance of the class. - and allows the underlying service provider to assign the most appropriate local IPv4 address and port number. If this constructor is used, the instance is set with an address family of IPv4 that cannot be changed or overwritten by a connect method call with an IPv6 target. - + and allows the underlying service provider to assign the most appropriate local IPv4 address and port number. If this constructor is used, the instance is set with an address family of IPv4 that cannot be changed or overwritten by a connect method call with an IPv6 target. + > [!NOTE] -> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - This constructor is not suitable for joining a multicast group because it does not perform socket binding. Also, it works only with IPv4 address types. - - - -## Examples - The following example demonstrates how to use the parameterless constructor to create an instance of the class. - +> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + This constructor is not suitable for joining a multicast group because it does not perform socket binding. Also, it works only with IPv4 address types. + + + +## Examples + The following example demonstrates how to use the parameterless constructor to create an instance of the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet4"::: + ]]> An error occurred when accessing the socket. @@ -190,25 +190,25 @@ The local port number from which you intend to communicate. Initializes a new instance of the class and binds it to the local port number provided. - and binds it to the port number from which you intend to communicate. Use this constructor if you are only interested in setting the local port number. The underlying service provider will assign the local IP address. If you pass 0 to the constructor, the underlying service provider will assign a port number. If this constructor is used, the instance is set with an address family of IPv4 that cannot be changed or overwritten by a connect method call with an IPv6 target. - + and binds it to the port number from which you intend to communicate. Use this constructor if you are only interested in setting the local port number. The underlying service provider will assign the local IP address. If you pass 0 to the constructor, the underlying service provider will assign a port number. If this constructor is used, the instance is set with an address family of IPv4 that cannot be changed or overwritten by a connect method call with an IPv6 target. + > [!NOTE] -> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - This constructor works only with IPv4 address types. - - - -## Examples - The following example demonstrates using a local port number to create an instance of the class. - +> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + This constructor works only with IPv4 address types. + + + +## Examples + The following example demonstrates using a local port number to create an instance of the class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet1"::: + ]]> The parameter is greater than or less than . @@ -252,25 +252,25 @@ An that represents the local endpoint to which you bind the UDP connection. Initializes a new instance of the class and binds it to the specified local endpoint. - and binds it to the specified by the `localEP` parameter. Before you call this constructor, you must create an using the IP address and port number from which you intend to send and receive data. You do not need to specify a local IP address and port number for sending and receiving data. If you do not, the underlying service provider will assign the most appropriate local IP address and port number. - - If this constructor is used, the instance is set with the address family specified by the `localEP` parameter that cannot be changed or overwritten by a connect method call with a different address family. - + and binds it to the specified by the `localEP` parameter. Before you call this constructor, you must create an using the IP address and port number from which you intend to send and receive data. You do not need to specify a local IP address and port number for sending and receiving data. If you do not, the underlying service provider will assign the most appropriate local IP address and port number. + + If this constructor is used, the instance is set with the address family specified by the `localEP` parameter that cannot be changed or overwritten by a connect method call with a different address family. + > [!NOTE] -> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following example demonstrates how to create an instance of the class using a local endpoint. - +> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following example demonstrates how to create an instance of the class using a local endpoint. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet2"::: + ]]> @@ -316,18 +316,18 @@ One of the values that specifies the addressing scheme of the socket. Initializes a new instance of the class. - value. To use an IPv6 address, pass the value. Passing any other value will cause the method to throw an . - - If this constructor is used, the instance is set with the address family specified by the `family` parameter that cannot be changed or overwritten by a connect method call with a different address family. - + value. To use an IPv6 address, pass the value. Passing any other value will cause the method to throw an . + + If this constructor is used, the instance is set with the address family specified by the `family` parameter that cannot be changed or overwritten by a connect method call with a different address family. + > [!NOTE] -> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - The is not suitable for joining a multicast group because it does not perform socket binding. - +> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + The is not suitable for joining a multicast group because it does not perform socket binding. + ]]> @@ -374,27 +374,27 @@ One of the values that specifies the addressing scheme of the socket. Initializes a new instance of the class and binds it to the local port number provided. - and binds it to the port number from which you intend to communicate. - - The `family` parameter determines whether the listener uses an IP version 4 address (IPv4) or an IP version 6 (IPv6) address. To use an IPv4 address, pass the value. To use an IPv6 address, pass the value. Passing any other value will cause the method to throw an . - - If this constructor is used, the instance is set with the address family specified by the `family` parameter that cannot be changed or overwritten by a connect method call with a different address family. - + and binds it to the port number from which you intend to communicate. + + The `family` parameter determines whether the listener uses an IP version 4 address (IPv4) or an IP version 6 (IPv6) address. To use an IPv4 address, pass the value. To use an IPv6 address, pass the value. Passing any other value will cause the method to throw an . + + If this constructor is used, the instance is set with the address family specified by the `family` parameter that cannot be changed or overwritten by a connect method call with a different address family. + > [!NOTE] -> If you receive a , use to obtain the specific error code. Once you have obtained this code, refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following code example shows how to create a UDP client to use in a multicast group. - +> If you receive a , use to obtain the specific error code. Once you have obtained this code, refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following code example shows how to create a UDP client to use in a multicast group. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/CPP/joinmulticastgroup.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/IPv6MulticastOption/Overview/joinmulticastgroup.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet3"::: + ]]> @@ -442,23 +442,23 @@ The remote port number to which you intend to connect. Initializes a new instance of the class and establishes a default remote host. - and establishes a remote host using the `hostname` and `port` parameters. Establishing a default remote host is optional. If you use this constructor, you do not have to specify a remote host in each call to the method. Specifying a default remote host limits you to that host only. You can change the default remote host at any time by calling the method. If you want to specify a remote host in your call to the method, do not use this constructor. - + and establishes a remote host using the `hostname` and `port` parameters. Establishing a default remote host is optional. If you use this constructor, you do not have to specify a remote host in each call to the method. Specifying a default remote host limits you to that host only. You can change the default remote host at any time by calling the method. If you want to specify a remote host in your call to the method, do not use this constructor. + > [!NOTE] -> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following example demonstrates how to create an instance of the class using a host name and port number. - +> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following example demonstrates how to create an instance of the class using a host name and port number. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet3"::: + ]]> @@ -518,11 +518,11 @@ if a connection is active; otherwise, . - can use this property to determine if a default remote host has been established. You can establish a default remote host by using the appropriate constructor or by calling the method. If you do establish a default remote host, you cannot specify a remote host in your call to . - + can use this property to determine if a default remote host has been established. You can establish a default remote host by using the appropriate constructor or by calling the method. If you do establish a default remote host, you cannot specify a remote host in your call to . + ]]> @@ -573,17 +573,17 @@ A Boolean value that specifies whether to enable or disable NAT traversal. Enables or disables Network Address Translation (NAT) traversal on a instance. - method is used to enable or disable NAT traversal for a instance. NAT traversal may be provided using Teredo, 6to4, or an ISATAP tunnel. - - When the `allowed` parameter is false, the option on the associated socket is set to . This explicitly disables NAT traversal for a instance. - - When the `allowed` parameter is true, the option on the associated socket is set to . This may allow NAT traversal for a depending on firewall rules in place on the system. - - A Teredo address is an IPv6 address with the prefix of 2001::/32. Teredo addresses can be returned through normal DNS name resolution or enumerated as an IPv6 address assigned to a local interface. - + method is used to enable or disable NAT traversal for a instance. NAT traversal may be provided using Teredo, 6to4, or an ISATAP tunnel. + + When the `allowed` parameter is false, the option on the associated socket is set to . This explicitly disables NAT traversal for a instance. + + When the `allowed` parameter is true, the option on the associated socket is set to . This may allow NAT traversal for a depending on firewall rules in place on the system. + + A Teredo address is an IPv6 address with the prefix of 2001::/32. Teredo addresses can be returned through normal DNS name resolution or enumerated as an IPv6 address assigned to a local interface. + ]]> @@ -629,24 +629,24 @@ Gets the amount of data received from the network that is available to read. The number of bytes of data received from the network. - property is used to determine the amount of data queued in the network buffer for reading. If data is available, call to get the data. If no data is available, the property returns 0. - - If the remote host shuts down or closes the connection, the property throws a . - + property is used to determine the amount of data queued in the network buffer for reading. If data is available, call to get the data. If no data is available, the property returns 0. + + If the remote host shuts down or closes the connection, the property throws a . + > [!NOTE] -> If you receive a , use to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following code example shows the use of the property. - +> If you receive a , use to obtain the specific error code and refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following code example shows the use of the property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient/CPP/newudpclient.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet1"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet1"::: + ]]> An error occurred while attempting to access the socket. @@ -695,23 +695,23 @@ Receives a datagram from a remote host asynchronously. An object that references the asynchronous receive. - operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. - - This method does not block until the operation is complete. To block until the operation is complete, use the method. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - - - -## Examples - The following code example uses to asynchronously receive a server response. - + operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. + + This method does not block until the operation is complete. To block until the operation is complete, use the method. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + + + +## Examples + The following code example uses to asynchronously receive a server response. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient1/cpp/asyncudp.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet1"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet1"::: + ]]> @@ -778,26 +778,26 @@ Sends a datagram to a remote host asynchronously. The destination was specified previously by a call to . An object that references the asynchronous send. - operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. - - This method does not block until the operation completes. To block until the operation is complete, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - - - -## Examples - The following code example uses to asynchronously send a server request. - + operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. + + This method does not block until the operation completes. To block until the operation is complete, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + + + +## Examples + The following code example uses to asynchronously send a server request. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient1/cpp/asyncudp.cpp" id="Snippet2"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet2"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet2"::: + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient1/cpp/asyncudp.cpp" id="Snippet3"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet3"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet3"::: + ]]> @@ -850,26 +850,26 @@ Sends a datagram to a destination asynchronously. The destination is specified by a . An object that references the asynchronous send. - operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. - - This method does not block until the operation is complete. To block until the operation is complete, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - - - -## Examples - The following code example uses to asynchronously send a server request. - + operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. + + This method does not block until the operation is complete. To block until the operation is complete, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + + + +## Examples + The following code example uses to asynchronously send a server request. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient1/cpp/asyncudp.cpp" id="Snippet2"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet2"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet2"::: + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient1/cpp/asyncudp.cpp" id="Snippet4"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet4"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet4"::: + ]]> @@ -924,26 +924,26 @@ Sends a datagram to a destination asynchronously. The destination is specified by the host name and port number. An object that references the asynchronous send. - operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. - - This method does not block until the operation is complete. To block until the operation is complete, use one of the method overloads. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - - - -## Examples - The following code example uses to asynchronously send a server request. - + operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. + + This method does not block until the operation is complete. To block until the operation is complete, use one of the method overloads. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + + + +## Examples + The following code example uses to asynchronously send a server request. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient1/cpp/asyncudp.cpp" id="Snippet2"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet2"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet2"::: + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient1/cpp/asyncudp.cpp" id="Snippet5"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet5"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet5"::: + ]]> @@ -998,20 +998,20 @@ Gets or sets the underlying network . The underlying Network . - creates a used to send and receive data over a network. Classes deriving from can use this property to get or set this . Use the underlying returned from if you require access beyond that which provides. You can also use to set the underlying to an existing . This is useful if you want to take advantage of the simplicity of using a pre-existing . - - - -## Examples - The following example demonstrates the use of the property. In this example, broadcasting is enabled for the underlying . - + creates a used to send and receive data over a network. Classes deriving from can use this property to get or set this . Use the underlying returned from if you require access beyond that which provides. You can also use to set the underlying to an existing . This is useful if you want to take advantage of the simplicity of using a pre-existing . + + + +## Examples + The following example demonstrates the use of the property. In this example, broadcasting is enabled for the underlying . + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.ProtectedMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Client/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.ProtectedMethodsAndPropertiesExample/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.ProtectedMethodsAndPropertiesExample/VB/source.vb" id="Snippet1"::: + ]]> @@ -1059,23 +1059,23 @@ Closes the UDP connection. - disables the underlying and releases all managed and unmanaged resources associated with the . - + disables the underlying and releases all managed and unmanaged resources associated with the . + > [!NOTE] -> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following example demonstrates closing a by calling the method. - +> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following example demonstrates closing a by calling the method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet15"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet15"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet15"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet15"::: + ]]> An error occurred when accessing the socket. @@ -1131,29 +1131,29 @@ An that specifies the network endpoint to which you intend to send data. Establishes a default remote host using the specified network endpoint. - method establishes a default remote host using the value specified in the `endPoint` parameter. Once established, you do not have to specify a remote host in each call to the method. - - Establishing a default remote host is optional. Specifying a default remote host limits you to that host only. If you want to send datagrams to a different remote host, you must make another call to the method or create another without a default remote host. If you have established a default remote host and you also provide a remote host in your call to the method, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - If you call the method, any datagrams that arrive from an address other than the specified default will be discarded. You cannot set the default remote host to a broadcast address using this method unless you inherit from , use the Client method to obtain the underlying , and set the socket option to . - - You can however, broadcast data to the default broadcast address, 255.255.255.255, if you specify in your call to the method. If your application requires greater control over broadcast addresses, you can also revert to using the class. - + method establishes a default remote host using the value specified in the `endPoint` parameter. Once established, you do not have to specify a remote host in each call to the method. + + Establishing a default remote host is optional. Specifying a default remote host limits you to that host only. If you want to send datagrams to a different remote host, you must make another call to the method or create another without a default remote host. If you have established a default remote host and you also provide a remote host in your call to the method, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + If you call the method, any datagrams that arrive from an address other than the specified default will be discarded. You cannot set the default remote host to a broadcast address using this method unless you inherit from , use the Client method to obtain the underlying , and set the socket option to . + + You can however, broadcast data to the default broadcast address, 255.255.255.255, if you specify in your call to the method. If your application requires greater control over broadcast addresses, you can also revert to using the class. + > [!NOTE] -> Since the UDP protocol is connectionless, the method does not block. Do not call the method if you intend to receive multicasted datagrams. - - - -## Examples - The following example uses an to establish a default remote host. - +> Since the UDP protocol is connectionless, the method does not block. Do not call the method if you intend to receive multicasted datagrams. + + + +## Examples + The following example uses an to establish a default remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet7"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet7"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet7"::: + ]]> An error occurred when accessing the socket. @@ -1206,29 +1206,29 @@ The port number to which you intend send data. Establishes a default remote host using the specified IP address and port number. - method establishes a default remote host using the values specified in the `addr` and `port` parameters. Once established, you do not have to specify a remote host in each call to the method. - - Establishing a default remote host is optional. Specifying a default remote host limits you to that host only. If you want to send datagrams to a different remote host, you must make another call to the method or create another without a default remote host. If you have established a default remote host and you also provide a remote host in your call to the method, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - If you call the method, any datagrams that arrive from an address other than the specified default will be discarded. You cannot set the default remote host to a broadcast address using this method unless you inherit from , use the client method to obtain the underlying , and set the socket option to . - - You can however, broadcast data to the default broadcast address, 255.255.255.255, if you specify in your call to the method. If your application requires greater control over broadcast addresses, you can also revert to using the class. - + method establishes a default remote host using the values specified in the `addr` and `port` parameters. Once established, you do not have to specify a remote host in each call to the method. + + Establishing a default remote host is optional. Specifying a default remote host limits you to that host only. If you want to send datagrams to a different remote host, you must make another call to the method or create another without a default remote host. If you have established a default remote host and you also provide a remote host in your call to the method, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + If you call the method, any datagrams that arrive from an address other than the specified default will be discarded. You cannot set the default remote host to a broadcast address using this method unless you inherit from , use the client method to obtain the underlying , and set the socket option to . + + You can however, broadcast data to the default broadcast address, 255.255.255.255, if you specify in your call to the method. If your application requires greater control over broadcast addresses, you can also revert to using the class. + > [!NOTE] -> Since the UDP protocol is connectionless, the method does not block. Do not call the method if you intend to receive multicasted datagrams. - - - -## Examples - The following example uses an IP address and port number to connect with a remote host. - +> Since the UDP protocol is connectionless, the method does not block. Do not call the method if you intend to receive multicasted datagrams. + + + +## Examples + The following example uses an IP address and port number to connect with a remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet6"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet6"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet6"::: + ]]> @@ -1284,31 +1284,31 @@ The port number on the remote host to which you intend to send data. Establishes a default remote host using the specified host name and port number. - method establishes a default remote host using the values specified in the `port` and `hostname` parameters. Once established, you do not have to specify a remote host in each call to the method. - - Establishing a default remote host is optional. Specifying a default remote host limits you to that host only. If you want to send datagrams to a different remote host, you must make another call to the method or create another without a default remote host. - - If you have established a default remote host and you also provide a remote host in your call to the method, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - If you call the method, any datagrams that arrive from an address other than the specified default will be discarded. You cannot set the default remote host to a broadcast address using this method unless you inherit from , use the client method to obtain the underlying , and set the socket option to . - - You can however, broadcast data to the default broadcast address, 255.255.255.255, if you specify in your call to the method. If your application requires greater control over broadcast addresses, you can also revert to using the class. - + method establishes a default remote host using the values specified in the `port` and `hostname` parameters. Once established, you do not have to specify a remote host in each call to the method. + + Establishing a default remote host is optional. Specifying a default remote host limits you to that host only. If you want to send datagrams to a different remote host, you must make another call to the method or create another without a default remote host. + + If you have established a default remote host and you also provide a remote host in your call to the method, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + If you call the method, any datagrams that arrive from an address other than the specified default will be discarded. You cannot set the default remote host to a broadcast address using this method unless you inherit from , use the client method to obtain the underlying , and set the socket option to . + + You can however, broadcast data to the default broadcast address, 255.255.255.255, if you specify in your call to the method. If your application requires greater control over broadcast addresses, you can also revert to using the class. + > [!NOTE] -> Since the UDP protocol is connectionless, the method does not block. Do not call the method if you intend to receive multicasted datagrams. - - - -## Examples - The following example uses the host name and port number to connect to a remote host. - +> Since the UDP protocol is connectionless, the method does not block. Do not call the method if you intend to receive multicasted datagrams. + + + +## Examples + The following example uses the host name and port number to connect to a remote host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet5"::: + ]]> The is closed. @@ -1400,19 +1400,19 @@ to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method, if it has been overridden. `Dispose()` invokes this method with the `disposing` parameter set to `true`. `Finalize` invokes this method with `disposing` set to `false`. - - When the `disposing` parameter is true, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - + + When the `disposing` parameter is true, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Overriding the Finalize Method](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ddae83kx(v=vs.100)). @@ -1454,19 +1454,19 @@ if the doesn't allow datagram fragmentation; otherwise, . The default is . - option is set, the datagram is discarded, and an Internet Control Message Protocol (ICMP) error message is sent back to the sender of the datagram. - - - -## Examples - The following code example shows the use of the property. - + option is set, the datagram is discarded, and an Internet Control Message Protocol (ICMP) error message is sent back to the sender of the datagram. + + + +## Examples + The following code example shows the use of the property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient/CPP/newudpclient.cpp" id="Snippet2"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet2"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet2"::: + ]]> This property can be set only for sockets that use the flag or the flag. @@ -1522,23 +1522,23 @@ The of the multicast group to leave. Leaves a multicast group. - method withdraws the from the multicast group identified by the specified . After calling the method, the underlying sends an Internet Group Management Protocol (IGMP) packet to the router, removing the router from the multicast group. After a withdraws from the group, it will no longer be able to receive datagrams sent to that group. - + method withdraws the from the multicast group identified by the specified . After calling the method, the underlying sends an Internet Group Management Protocol (IGMP) packet to the router, removing the router from the multicast group. After a withdraws from the group, it will no longer be able to receive datagrams sent to that group. + > [!NOTE] -> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following example demonstrates how to drop a multicast group by providing a multicast address. - +> If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following example demonstrates how to drop a multicast group by providing a multicast address. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/CPP/joinmulticastgroup.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/IPv6MulticastOption/Overview/joinmulticastgroup.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet2"::: + ]]> The underlying has been closed. @@ -1591,23 +1591,23 @@ The local address of the multicast group to leave. Leaves a multicast group. - method withdraws the from the multicast group identified by the specified . After calling the method, the underlying sends an Internet Group Management Protocol (IGMP) packet to the router, removing the router from the multicast group. After a withdraws from the group, it will no longer be able to receive datagrams sent to that group. - + method withdraws the from the multicast group identified by the specified . After calling the method, the underlying sends an Internet Group Management Protocol (IGMP) packet to the router, removing the router from the multicast group. After a withdraws from the group, it will no longer be able to receive datagrams sent to that group. + > [!NOTE] -> If you receive a , use the property to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following code example demonstrates how to drop a multicast group by providing a multicast address. - +> If you receive a , use the property to obtain the specific error code. After you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following code example demonstrates how to drop a multicast group by providing a multicast address. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/CPP/joinmulticastgroup.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/IPv6MulticastOption/Overview/joinmulticastgroup.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet2"::: + ]]> The underlying has been closed. @@ -1655,19 +1655,19 @@ if the allows sending broadcast packets; otherwise, . The default is . - property. - + property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient/CPP/newudpclient.cpp" id="Snippet3"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet3"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet3"::: + ]]> @@ -1714,21 +1714,21 @@ Ends a pending asynchronous receive. If successful, an array of bytes that contains datagram data. - method. - - - -## Examples - The following code example uses to complete an asynchronous receive of a server response. - + method. + + + +## Examples + The following code example uses to complete an asynchronous receive of a server response. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient1/cpp/asyncudp.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet1"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet1"::: + ]]> @@ -1780,21 +1780,21 @@ Ends a pending asynchronous send. If successful, the number of bytes sent to the . - method. - - - -## Examples - The following code example uses to complete an asynchronous send of a server request. - + method. + + + +## Examples + The following code example uses to complete an asynchronous send of a server request. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient1/cpp/asyncudp.cpp" id="Snippet2"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet2"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/BeginReceive/asyncudp.cs" id="Snippet2"::: + ]]> @@ -1844,21 +1844,21 @@ if the allows only one client to use a specific port; otherwise, . The default is for Windows Server 2003 and Windows XP Service Pack 2 and later, and for all other versions. - property to prevent multiple clients from using a specific port. - - This property must be set before the underlying socket is bound to a client port. If you call , , , or , the client port is bound as a side effect of the constructor, and you cannot subsequently set the property - - - -## Examples - The following code example creates a , and gets and sets the property. - + property to prevent multiple clients from using a specific port. + + This property must be set before the underlying socket is bound to a client port. If you call , , , or , the client port is bound as a side effect of the constructor, and you cannot subsequently set the property + + + +## Examples + The following code example creates a , and gets and sets the property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient/CPP/newudpclient.cpp" id="Snippet4"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet4"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet4"::: + ]]> An error occurred when attempting to access the underlying socket. @@ -1943,33 +1943,33 @@ The multicast of the group you want to join. Adds a to a multicast group. - method subscribes the to a multicast group using the specified . After calling the method, the underlying sends an Internet Group Management Protocol (IGMP) packet to the router requesting membership to the multicast group. The multicast address range is 224.0.0.0 to 239.255.255.255. If you specify an address outside this range or if the router to which the request is made is not multicast enabled, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. Once the is listed with the router as a member of the multicast group, it will be able to receive multicasted datagrams sent to the specified . - + method subscribes the to a multicast group using the specified . After calling the method, the underlying sends an Internet Group Management Protocol (IGMP) packet to the router requesting membership to the multicast group. The multicast address range is 224.0.0.0 to 239.255.255.255. If you specify an address outside this range or if the router to which the request is made is not multicast enabled, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. Once the is listed with the router as a member of the multicast group, it will be able to receive multicasted datagrams sent to the specified . + > [!NOTE] -> You must create the using the multicast port number; otherwise, you will not be able to receive multicasted datagrams. Do not call the method prior to calling the method, or the method will not work. You do not need to belong to a multicast group to send datagrams to a multicast IP address. - - Before joining a multicast group, make sure the socket is bound to the port or endpoint. You do that by calling one of the constructors that accept a port or an endpoint as a parameter. - - To stop receiving multicasted datagrams, call the method and provide the of the group from which you would like to withdraw. - +> You must create the using the multicast port number; otherwise, you will not be able to receive multicasted datagrams. Do not call the method prior to calling the method, or the method will not work. You do not need to belong to a multicast group to send datagrams to a multicast IP address. + + Before joining a multicast group, make sure the socket is bound to the port or endpoint. You do that by calling one of the constructors that accept a port or an endpoint as a parameter. + + To stop receiving multicasted datagrams, call the method and provide the of the group from which you would like to withdraw. + > [!NOTE] -> In the IPv6 case, there are several multicast address ranges you can choose from. Please, refer to the IETF RFC 2375. - +> In the IPv6 case, there are several multicast address ranges you can choose from. Please, refer to the IETF RFC 2375. + > [!NOTE] -> You cannot call on a constructed without a specific local port (that is, using the or constructor). - - - -## Examples - The following code example demonstrates how to join a multicast group by providing a multicast address. - +> You cannot call on a constructed without a specific local port (that is, using the or constructor). + + + +## Examples + The following code example demonstrates how to join a multicast group by providing a multicast address. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/CPP/joinmulticastgroup.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/IPv6MulticastOption/Overview/joinmulticastgroup.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet1"::: + ]]> The underlying has been closed. @@ -2020,26 +2020,26 @@ The multicast of the group you want to join. Adds a to a multicast group. - [!NOTE] -> There are several multicast address ranges to choose from. Refer to the IETF RFC 2375. - +> There are several multicast address ranges to choose from. Refer to the IETF RFC 2375. + > [!NOTE] -> You cannot call on a constructed without a specific local port (that is, using the or constructor). - - - -## Examples +> You cannot call on a constructed without a specific local port (that is, using the or constructor). + + + +## Examples :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/CPP/joinmulticastgroup.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/IPv6MulticastOption/Overview/joinmulticastgroup.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/VB/joinmulticastgroup.vb" id="Snippet5"::: + ]]> The underlying has been closed. @@ -2088,30 +2088,30 @@ The Time to Live (TTL), measured in router hops. Adds a to a multicast group with the specified Time to Live (TTL). - method subscribes the to a multicast group using the specified . After calling the method, the underlying sends an Internet Group Management Protocol (IGMP) packet to the router requesting membership to the multicast group. The multicast address range is 224.0.0.0 to 239.255.255.255. If you specify an address outside this range or if the router to which the request is made is not multicast enabled, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. The `timeToLive` parameter specifies how many router hops will be allowed for a multicasted datagram before being discarded. Once the is listed with the router as a member of the multicast group, it will be able to receive multicasted datagrams sent to the specified . - + method subscribes the to a multicast group using the specified . After calling the method, the underlying sends an Internet Group Management Protocol (IGMP) packet to the router requesting membership to the multicast group. The multicast address range is 224.0.0.0 to 239.255.255.255. If you specify an address outside this range or if the router to which the request is made is not multicast enabled, will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. The `timeToLive` parameter specifies how many router hops will be allowed for a multicasted datagram before being discarded. Once the is listed with the router as a member of the multicast group, it will be able to receive multicasted datagrams sent to the specified . + > [!NOTE] -> You must create the using the multicast port number otherwise you will not be able to receive multicasted datagrams. Do not call the method prior to calling the method or the receive method will not work. You do not need to belong to a multicast group to send datagrams to a multicast IP address. - - Before joining a multicast group make sure the socket is bound to the port or endpoint. You do that by calling one of the constructors that accept as parameter a port or an endpoint. - - To stop receiving multicasted datagrams, call the method and provide the of the group from which you would like to withdraw. - +> You must create the using the multicast port number otherwise you will not be able to receive multicasted datagrams. Do not call the method prior to calling the method or the receive method will not work. You do not need to belong to a multicast group to send datagrams to a multicast IP address. + + Before joining a multicast group make sure the socket is bound to the port or endpoint. You do that by calling one of the constructors that accept as parameter a port or an endpoint. + + To stop receiving multicasted datagrams, call the method and provide the of the group from which you would like to withdraw. + > [!NOTE] -> You cannot call on a constructed without a specific local port (that is, using the or constructor). - - - -## Examples - The following example demonstrates how to join a multicast group by providing two parameters, a multicast address, and a number that represents the TTL. - +> You cannot call on a constructed without a specific local port (that is, using the or constructor). + + + +## Examples + The following example demonstrates how to join a multicast group by providing two parameters, a multicast address, and a number that represents the TTL. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet13"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet13"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet13"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet13"::: + ]]> The TTL provided is not between 0 and 255 @@ -2164,25 +2164,25 @@ The local . Adds a to a multicast group. - [!NOTE] -> There are several multicast address ranges to choose from. You can find them in the IETF RFC 2375. - +> There are several multicast address ranges to choose from. You can find them in the IETF RFC 2375. + > [!NOTE] -> You cannot call on a constructed without a specific local port (that is, using the or constructor). - - - -## Examples - The following code example shows the use of the method. - +> You cannot call on a constructed without a specific local port (that is, using the or constructor). + + + +## Examples + The following code example shows the use of the method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient/CPP/newudpclient.cpp" id="Snippet6"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet6"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet6"::: + ]]> The underlying has been closed. @@ -2226,19 +2226,19 @@ if the receives outgoing multicast packets; otherwise, . - property. - + property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient/CPP/newudpclient.cpp" id="Snippet7"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet7"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet7"::: + ]]> @@ -2291,27 +2291,27 @@ Returns a UDP datagram that was sent by a remote host. An array of type that contains datagram data. - method will block until a datagram arrives from a remote host. When data is available, the method will read the first enqueued datagram and return the data portion as a byte array. This method populates the `remoteEP` parameter with the and port number of the sender. - - If you specify a default remote host in the method, the method will accept datagrams from that host only. All other datagrams will be discarded. - - If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - + method will block until a datagram arrives from a remote host. When data is available, the method will read the first enqueued datagram and return the data portion as a byte array. This method populates the `remoteEP` parameter with the and port number of the sender. + + If you specify a default remote host in the method, the method will accept datagrams from that host only. All other datagrams will be discarded. + + If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!NOTE] -> If you intend to receive multicasted datagrams, do not call the method prior to calling the method. The you use to receive datagrams must be created using the multicast port number. - - - -## Examples - The following example demonstrates the method. The method blocks execution until it receives a message. Using the passed to , the identity of the responding host is revealed. - +> If you intend to receive multicasted datagrams, do not call the method prior to calling the method. The you use to receive datagrams must be created using the multicast port number. + + + +## Examples + The following example demonstrates the method. The method blocks execution until it receives a message. Using the passed to , the identity of the responding host is revealed. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet11"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet11"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet11"::: + ]]> The underlying has been closed. @@ -2358,18 +2358,18 @@ Returns a UDP datagram asynchronously that was sent by a remote host. The task object representing the asynchronous operation. - > object will complete after the UDP packet has been received. - - If you specify a default remote host in the method, this method will accept datagrams from that host only. All other datagrams will be discarded. - - If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - + > object will complete after the UDP packet has been received. + + If you specify a default remote host in the method, this method will accept datagrams from that host only. All other datagrams will be discarded. + + If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + > [!WARNING] -> If you intend to receive multicasted datagrams, do not call the method prior to calling this method. The you use to receive datagrams must be created using the multicast port number. - +> If you intend to receive multicasted datagrams, do not call the method prior to calling this method. The you use to receive datagrams must be created using the multicast port number. + ]]> The underlying has been closed. @@ -2405,6 +2405,7 @@ To be added. The underlying has been closed. An error occurred when accessing the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2491,22 +2492,22 @@ Sends a UDP datagram to a remote host. The number of bytes sent. - method and returns the number of bytes sent. If you do not call before calling this overload, the method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - If you want to send datagrams to a different remote host, you must call the method and specify the desired remote host. Use either of the other method overloads to send datagrams to a broadcast address. - - - -## Examples - The following example demonstrates the method. You must establish a default remote host prior to using this overload. - + method and returns the number of bytes sent. If you do not call before calling this overload, the method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + If you want to send datagrams to a different remote host, you must call the method and specify the desired remote host. Use either of the other method overloads to send datagrams to a broadcast address. + + + +## Examples + The following example demonstrates the method. You must establish a default remote host prior to using this overload. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet10"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet10"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet10"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet10"::: + ]]> @@ -2598,25 +2599,25 @@ Sends a UDP datagram to the host at the specified remote endpoint. The number of bytes sent. - method sends datagrams to the specified endpoint and returns the number of bytes successfully sent. Before calling this overload, you must first create an using the IP address and port number of the remote host to which your datagrams will be delivered. You can send datagrams to the default broadcast address, 255.255.255.255, by specifying for the property of the . After you have created this , pass it to the method as the `endPoint` parameter. - - If you want to send datagrams to any other broadcast address, use the method to obtain the underlying , and set the socket option to . You can also revert to using the class. - + method sends datagrams to the specified endpoint and returns the number of bytes successfully sent. Before calling this overload, you must first create an using the IP address and port number of the remote host to which your datagrams will be delivered. You can send datagrams to the default broadcast address, 255.255.255.255, by specifying for the property of the . After you have created this , pass it to the method as the `endPoint` parameter. + + If you want to send datagrams to any other broadcast address, use the method to obtain the underlying , and set the socket option to . You can also revert to using the class. + > [!NOTE] -> Do not provide an `endPoint` parameter to this method if you have already established a remote host with the method. If you do, the method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following example demonstrates the method. This example uses an to specify the target host. - +> Do not provide an `endPoint` parameter to this method if you have already established a remote host with the method. If you do, the method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following example demonstrates the method. This example uses an to specify the target host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet8"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet8"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet8"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet8"::: + ]]> @@ -2715,25 +2716,25 @@ Sends a UDP datagram to a specified port on a specified remote host. The number of bytes sent. - method sends datagrams to the values specified by the `hostname` and `port` parameters and returns the number of bytes successfully sent. You can send datagrams to the default broadcast address by specifying "255.255.255.255" for the `hostname` parameter value. - - If you want to send datagrams to any other broadcast address, use the method to obtain the underlying , and set the socket option to . You can also revert to using the class. - + method sends datagrams to the values specified by the `hostname` and `port` parameters and returns the number of bytes successfully sent. You can send datagrams to the default broadcast address by specifying "255.255.255.255" for the `hostname` parameter value. + + If you want to send datagrams to any other broadcast address, use the method to obtain the underlying , and set the socket option to . You can also revert to using the class. + > [!NOTE] -> Do not provide a host name or port number to this method if you have already established a remote host with the method. If you do, the method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - - -## Examples - The following example demonstrates the method. This example uses a host name and a port number to identify the target host. - +> Do not provide a host name or port number to this method if you have already established a remote host with the method. If you do, the method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + + +## Examples + The following example demonstrates the method. This example uses a host name and a port number to identify the target host. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/CPP/source.cpp" id="Snippet9"::: :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/.ctor/source.cs" id="Snippet9"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet9"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic UdpClient.PublicMethodsAndPropertiesExample/VB/source.vb" id="Snippet9"::: + ]]> @@ -2796,13 +2797,13 @@ Sends a UDP datagram asynchronously to a remote host. Returns . - method. If you do not call before calling this overload, the method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - - If you want to send datagrams to a different remote host, you must call the method and specify the desired remote host. Use either of the other method overloads to send datagrams to a broadcast address. - + method. If you do not call before calling this overload, the method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + + If you want to send datagrams to a different remote host, you must call the method and specify the desired remote host. Use either of the other method overloads to send datagrams to a broadcast address. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -2844,6 +2845,7 @@ To be added. The is closed. An error occurred when accessing the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2890,16 +2892,16 @@ Sends a UDP datagram asynchronously to a remote host. Returns . - using the IP address and port number of the remote host to which your datagrams will be delivered. You can send datagrams to the default broadcast address, 255.255.255.255, by specifying for the property of the . After you have created this , pass it to this method as the `endPoint` parameter. - - If you want to send datagrams to any other broadcast address, use the method to obtain the underlying , and set the socket option to . You can also revert to using the class. - + using the IP address and port number of the remote host to which your datagrams will be delivered. You can send datagrams to the default broadcast address, 255.255.255.255, by specifying for the property of the . After you have created this , pass it to this method as the `endPoint` parameter. + + If you want to send datagrams to any other broadcast address, use the method to obtain the underlying , and set the socket option to . You can also revert to using the class. + > [!WARNING] -> Do not provide an `endPoint` parameter to this method if you have already established a remote host with the method. If you do, this method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> Do not provide an `endPoint` parameter to this method if you have already established a remote host with the method. If you do, this method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -2947,6 +2949,7 @@ has already established a default remote host and is not . The is closed. An error occurred when accessing the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2995,16 +2998,16 @@ Sends a UDP datagram asynchronously to a remote host. Returns . - method to obtain the underlying , and set the socket option to . You can also revert to using the class. - + method to obtain the underlying , and set the socket option to . You can also revert to using the class. + > [!WARNING] -> Do not provide a host name or port number to this method if you have already established a remote host with the method. If you do, this method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. - +> Do not provide a host name or port number to this method if you have already established a remote host with the method. If you do, this method will throw a . If you receive a , use to obtain the specific error code. Once you have obtained this code, you can refer to the [Windows Sockets version 2 API error code](/windows/desktop/winsock/windows-sockets-error-codes-2) documentation for a detailed description of the error. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -3051,6 +3054,7 @@ The has already established a default remote host. The is closed. An error occurred when accessing the socket. + The cancellation token was canceled. This exception is stored into the returned task. @@ -3091,10 +3095,10 @@ . The IDisposable.Dispose method leaves the in an unusable state. After calling IDisposable.Dispose, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). -> [!NOTE] +> [!NOTE] > Always call IDisposable.Dispose before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's `Finalize` method. ]]> @@ -3138,19 +3142,19 @@ Call IDisposable.Dispose when you are finished using the Gets or sets a value that specifies the Time to Live (TTL) value of Internet Protocol (IP) packets sent by the . The TTL value. - property. - + property. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient/CPP/newudpclient.cpp" id="Snippet5"::: - :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet5"::: - + :::code language="csharp" source="~/snippets/csharp/System.Net.Sockets/UdpClient/Available/newudpclient.cs" id="Snippet5"::: + ]]> diff --git a/xml/System.Net.WebSockets/ClientWebSocket.xml b/xml/System.Net.WebSockets/ClientWebSocket.xml index ab872dd6f69..c555e35fdf1 100644 --- a/xml/System.Net.WebSockets/ClientWebSocket.xml +++ b/xml/System.Net.WebSockets/ClientWebSocket.xml @@ -191,6 +191,7 @@ Exactly one send and one receive is supported on each + The cancellation token was canceled. This exception is stored into the returned task. @@ -250,6 +251,7 @@ Exactly one send and one receive is supported on each + The cancellation token was canceled. This exception is stored into the returned task. @@ -382,23 +384,24 @@ Exactly one send and one receive is supported on each object will complete after the connect request on the instance has completed. - + The WebSocket handshake request has default headers for HTTP/1.1 request: - + `Connection: Upgrade` - + `Upgrade: websocket` - + `Sec-WebSocket-Key: [generated key]` - + For HTTP/2 request: - + `:protocol: websocket` - + By default, HTTP/1.1 will be used. To change HTTP version used or enable HTTP version upgrade/downgrade, see option and option. ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -431,6 +434,7 @@ Exactly one send and one receive is supported on each Connects to a WebSocket server as an asynchronous operation. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -610,6 +614,7 @@ Exactly one send and one receive is supported on each The is not connected. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -656,6 +661,7 @@ Exactly one send and one receive is supported on each The is not connected. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -716,6 +722,7 @@ Exactly one send and one receive is supported on each The is not connected. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -768,6 +775,7 @@ Exactly one send and one receive is supported on each The is not connected. The has been closed. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net.WebSockets/WebSocket.xml b/xml/System.Net.WebSockets/WebSocket.xml index 20061295fd8..42aa57cf22c 100644 --- a/xml/System.Net.WebSockets/WebSocket.xml +++ b/xml/System.Net.WebSockets/WebSocket.xml @@ -41,13 +41,13 @@ The WebSocket class allows applications to send and receive data after the WebSocket upgrade has completed. - namespace are supported on Windows 7, Windows Vista SP2, and Windows Server 2008. However, the only public implementations of client and server WebSockets are supported on Windows 8 and Windows Server 2012. The classes and class elements in the namespace that are supported on Windows 7, Windows Vista SP2, and Windows Server 2008 are abstract classes. This allows an application developer to inherit and extend these abstract classes with an actual implementation of client WebSockets. Exactly one send and one receive is supported on each object in parallel. Issuing multiple sends or multiple receives at the same time (for example, without awaiting, or from multiple threads without synchronization) is *not supported* and will result in an *undefined behavior*. Ensure that the previous operation is awaited (or completed) before issuing the next one. Serialize the access via whatever mechanism works best for you, for example, by using a lock or a semaphore. - + ]]> @@ -166,15 +166,16 @@ Exactly one send and one receive is supported on each Closes the WebSocket connection as an asynchronous operation using the close handshake defined in the WebSocket protocol specification section 7. The task object representing the asynchronous operation. - object will complete after the WebSocket has been closed. - - This method closes the WebSocket connection using the close handshake defined in the [WebSocket protocol specification](https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-06) section 7. - + object will complete after the WebSocket has been closed. + + This method closes the WebSocket connection using the close handshake defined in the [WebSocket protocol specification](https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-06) section 7. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -221,13 +222,14 @@ Exactly one send and one receive is supported on each Initiates or completes the close handshake defined in the WebSocket protocol specification section 7. The task object representing the asynchronous operation. - object will complete after the output on the WebSocket has been closed. - + object will complete after the output on the WebSocket has been closed. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -265,11 +267,11 @@ Exactly one send and one receive is supported on each Indicates the reason why the remote endpoint initiated the close handshake. Returns . - @@ -764,15 +766,16 @@ Exactly one send and one receive is supported on each Receives data from the connection asynchronously. The task object representing the asynchronous operation. The property on the task object returns a object that represents the received data. - object will complete after the data has been received on the . - + object will complete after the data has been received on the . + Exactly one send and one receive is supported on each object in parallel. Issuing multiple receives at the same time is *not supported* and will result in an *undefined behavior*. You should serialize receive operations via whatever mechanism works best for you, for example, by using a lock or a semaphore. - + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -808,6 +811,7 @@ Exactly one send and one receive is supported on each Receives data from the connection asynchronously. The task object representing the asynchronous operation. The property on the task object returns a object that represents the received data. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -906,15 +910,16 @@ Exactly one send and one receive is supported on each Sends data over the connection asynchronously. The task object representing the asynchronous operation. - object will complete after the data has been sent on the . - -Exactly one send and one receive is supported on each object in parallel. Issuing multiple sends at the same time is *not supported* and will result in an *undefined behavior*. You should serialize send operations via whatever mechanism works best for you, for example, by using a lock or a semaphore. - + object will complete after the data has been sent on the . + +Exactly one send and one receive is supported on each object in parallel. Issuing multiple sends at the same time is *not supported* and will result in an *undefined behavior*. You should serialize send operations via whatever mechanism works best for you, for example, by using a lock or a semaphore. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -955,6 +960,7 @@ Exactly one send and one receive is supported on each Sends data over the connection asynchronously. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -990,6 +996,7 @@ Exactly one send and one receive is supported on each Sends data over the connection asynchronously. The task object representing the asynchronous operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Net/Dns.xml b/xml/System.Net/Dns.xml index 64a2aa44f6e..802e9868688 100644 --- a/xml/System.Net/Dns.xml +++ b/xml/System.Net/Dns.xml @@ -44,22 +44,22 @@ Provides simple domain name resolution functionality. - class is a static class that retrieves information about a specific host from the Internet Domain Name System (DNS). - - The host information from the DNS query is returned in an instance of the class. If the specified host has more than one entry in the DNS database, contains multiple IP addresses and aliases. - - - -## Examples - The following example queries the DNS database for information on the host `www.contoso.com`. - + class is a static class that retrieves information about a specific host from the Internet Domain Name System (DNS). + + The host information from the DNS query is returned in an instance of the class. If the specified host has more than one entry in the DNS database, contains multiple IP addresses and aliases. + + + +## Examples + The following example queries the DNS database for information on the host `www.contoso.com`. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Classic Dns Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/Overview/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic Dns Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Classic Dns Example/VB/source.vb" id="Snippet1"::: + ]]> @@ -108,22 +108,22 @@ Asynchronously returns the Internet Protocol (IP) addresses for the specified host. An instance that references the asynchronous request. - method asynchronously queries a DNS server for the IP addresses that are associated with a host name. If `hostNameOrAddress` is an IP address, this address is returned without querying the DNS server. - + method asynchronously queries a DNS server for the IP addresses that are associated with a host name. If `hostNameOrAddress` is an IP address, this address is returned without querying the DNS server. + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + If an empty string is passed as the `hostNameOrAddress` argument, then this method returns the IPv4 and IPv6 addresses of the local host. - - The asynchronous operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. - - This method does not block until the operation is complete. To block until the operation is complete, use the method. - - For more information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - + + The asynchronous operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. + + This method does not block until the operation is complete. To block until the operation is complete, use the method. + + For more information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + ]]> @@ -197,18 +197,18 @@ Begins an asynchronous request for information about the specified DNS host name. An instance that references the asynchronous request. - operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. - - This method does not block until the operation is complete. To block until the operation is complete, use the method. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - + operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. + + This method does not block until the operation is complete. To block until the operation is complete, use the method. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + ]]> @@ -271,28 +271,28 @@ Asynchronously resolves an IP address to an instance. An instance that references the asynchronous request. - method asynchronously queries a DNS server for the IP addresses and aliases associated with an IP address. - - **Note** This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - The asynchronous operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. - - This method does not block until the operation is complete. To block until the operation is complete, use the method. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) - - - -## Examples - The following code example uses the method to resolve an IP address to an instance. - + method asynchronously queries a DNS server for the IP addresses and aliases associated with an IP address. + + **Note** This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + The asynchronous operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. + + This method does not block until the operation is complete. To block until the operation is complete, use the method. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously) + + + +## Examples + The following code example uses the method to resolve an IP address to an instance. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Dns/CPP/dnsnewmethods.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/BeginGetHostEntry/dnsnewmethods.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet2"::: + ]]> @@ -346,28 +346,28 @@ Asynchronously resolves a host name or IP address to an instance. An instance that references the asynchronous request. - method queries a DNS server for the IP address that is associated with a host name or IP address. - - **Note** This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - The asynchronous operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. - - This method does not block until the operation is complete. To block until the operation is complete, use the method. - - For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - - - -## Examples - The following code example uses the method to resolve an IP address to an instance. - + method queries a DNS server for the IP address that is associated with a host name or IP address. + + **Note** This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + The asynchronous operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. + + This method does not block until the operation is complete. To block until the operation is complete, use the method. + + For detailed information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + + + +## Examples + The following code example uses the method to resolve an IP address to an instance. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Dns/CPP/dnsnewmethods.cpp" id="Snippet2"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/BeginGetHostEntry/dnsnewmethods.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet2"::: + ]]> @@ -441,27 +441,27 @@ Begins an asynchronous request to resolve a DNS host name or IP address to an instance. An instance that references the asynchronous request. - operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. - - This method does not block until the operation is complete. To block until the operation is complete, use the method. - - For more information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). - + operation must be completed by calling the method. Typically, the method is invoked by the `requestCallback` delegate. + + This method does not block until the operation is complete. To block until the operation is complete, use the method. + + For more information about using the asynchronous programming model, see [Calling Synchronous Methods Asynchronously](/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously). + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following example uses to resolve a DNS host name to an . - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following example uses to resolve a DNS host name to an . + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Dns_Begin_EndResolve/CPP/dns_begin_endresolve.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/BeginResolve/dns_begin_endresolve.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_Begin_EndResolve/VB/dns_begin_endresolve.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_Begin_EndResolve/VB/dns_begin_endresolve.vb" id="Snippet1"::: + ]]> @@ -509,16 +509,16 @@ Ends an asynchronous request for DNS information. An array of type that holds the IP addresses for the host specified by the parameter of . - method queries a DNS server for the IP addresses associated with a host name. If `hostNameOrAddress` is an IP address, this address is returned without querying the DNS server. - + method queries a DNS server for the IP addresses associated with a host name. If `hostNameOrAddress` is an IP address, this address is returned without querying the DNS server. + If an empty string is passed as the `hostNameOrAddress` argument, then this method returns the IPv4 and IPv6 addresses of the local host. - + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + ]]> @@ -581,18 +581,18 @@ Ends an asynchronous request for DNS information. An object that contains DNS information about a host. - method. - - If the property is set to `true`, the property of the instance returned is not populated by this method and will always be empty. - + method. + + If the property is set to `true`, the property of the instance returned is not populated by this method and will always be empty. + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + ]]> @@ -639,18 +639,18 @@ Ends an asynchronous request for DNS information. An instance that contains address information about the host. - property of the instance returned is not populated by this method and will always be empty. - - To perform this operation synchronously, use a method. - + property of the instance returned is not populated by this method and will always be empty. + + To perform this operation synchronously, use a method. + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + ]]> @@ -715,27 +715,27 @@ Ends an asynchronous request for DNS information. An object that contains DNS information about a host. - is set to `true`, the property of the instance returned is not populated by this method and will always be empty. - - To perform this operation synchronously, use the method. - + is set to `true`, the property of the instance returned is not populated by this method and will always be empty. + + To perform this operation synchronously, use the method. + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following example ends an asynchronous request for DNS host information. - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following example ends an asynchronous request for DNS host information. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Dns_Begin_EndResolve/CPP/dns_begin_endresolve.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/BeginResolve/dns_begin_endresolve.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_Begin_EndResolve/VB/dns_begin_endresolve.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_Begin_EndResolve/VB/dns_begin_endresolve.vb" id="Snippet1"::: + ]]> @@ -782,29 +782,29 @@ Returns the Internet Protocol (IP) addresses for the specified host. An array of type that holds the IP addresses for the host that is specified by the parameter. - method queries the DNS subsystem for the IP addresses associated with a host name. If `hostNameOrAddress` is an IP address, this address is returned without querying the DNS server. - + If an empty string is passed as the `hostNameOrAddress` argument, then this method returns the IPv4 and IPv6 addresses of the local host. - - IPv6 addresses are filtered from the results of the method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results were available for the `hostNameOrAddress` parameter. - + + IPv6 addresses are filtered from the results of the method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results were available for the `hostNameOrAddress` parameter. + This method is implemented using the underlying operating system's name resolution APIs (such as the Win32 API getaddrinfo on Windows, and equivalent APIs on other platforms). If a host is described in the `hosts` file, the IP address or addresses there will be returned without querying the DNS server. > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following code example uses the method to resolve an IP address to an array of type . - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following code example uses the method to resolve an IP address to an array of type . + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Dns/CPP/dnsnewmethods.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/BeginGetHostEntry/dnsnewmethods.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet3"::: + ]]> @@ -885,13 +885,13 @@ Returns the Internet Protocol (IP) addresses for the specified host as an asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns an array of type that holds the IP addresses for the host that is specified by the parameter. - object will complete after the `hostNameOrAddress` has been resolved. - - This method queries a DNS server for the IP addresses associated with a host name. If `hostNameOrAddress` is an IP address, this address is returned without querying the DNS server. - + object will complete after the `hostNameOrAddress` has been resolved. + + This method queries a DNS server for the IP addresses associated with a host name. If `hostNameOrAddress` is an IP address, this address is returned without querying the DNS server. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -933,6 +933,7 @@ Returns the Internet Protocol (IP) addresses for the specified host as an asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns an array of type that holds the IP addresses for the host that is specified by the parameter. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -965,6 +966,7 @@ Returns the Internet Protocol (IP) addresses for the specified host as an asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns an array of type that holds the IP addresses for the host that is specified by the parameter. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1035,22 +1037,22 @@ Creates an instance from the specified . An instance. - [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following example creates a from an . - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following example creates a from an . + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Dns_GetHostByAddress_IPAddress/CPP/dns_gethostbyaddress_ipaddress.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/GetHostByAddress/dns_gethostbyaddress_ipaddress.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_GetHostByAddress_IPAddress/VB/dns_gethostbyaddress_ipaddress.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_GetHostByAddress_IPAddress/VB/dns_gethostbyaddress_ipaddress.vb" id="Snippet1"::: + ]]> @@ -1116,13 +1118,13 @@ Creates an instance from an IP address. An instance. - [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + ]]> @@ -1190,27 +1192,27 @@ Gets the DNS information for the specified DNS host name. An object that contains host information for the address specified in . - method queries the Internet DNS server for host information. If you pass an empty string as the host name, this method retrieves the standard host name for the local computer. - - For asynchronous access to DNS information, use the and methods. - - If the property is set to `true`, the property of the instance returned is not populated by this method and will always be empty. - + method queries the Internet DNS server for host information. If you pass an empty string as the host name, this method retrieves the standard host name for the local computer. + + For asynchronous access to DNS information, use the and methods. + + If the property is set to `true`, the property of the instance returned is not populated by this method and will always be empty. + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following example uses the method to get the DNS information for the specified DNS host name. - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following example uses the method to get the DNS information for the specified DNS host name. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Dns_GetHostByName/CPP/dns_gethostbyname.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/GetHostByName/dns_gethostbyname.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_GetHostByName/VB/dns_gethostbyname.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_GetHostByName/VB/dns_gethostbyname.vb" id="Snippet1"::: + ]]> @@ -1268,25 +1270,25 @@ Resolves an IP address to an instance. An instance that contains address information about the host specified in . - method queries a DNS server for the IP addresses and aliases associated with an IP address. - - IPv6 addresses are filtered from the results of the method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results were available for the `address` parameter. - - The property of the instance returned is not populated by this method and will always be empty. - + method queries a DNS server for the IP addresses and aliases associated with an IP address. + + IPv6 addresses are filtered from the results of the method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results were available for the `address` parameter. + + The property of the instance returned is not populated by this method and will always be empty. + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + +## Examples + The following code example uses the method to resolve an IP address to an instance. -## Examples - The following code example uses the method to resolve an IP address to an instance. - :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Dns/CPP/dnsnewmethods.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/BeginGetHostEntry/dnsnewmethods.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet4"::: + ]]> @@ -1335,47 +1337,47 @@ Resolves a host name or IP address to an instance. An instance that contains address information about the host specified in . - method queries a DNS server for the IP address that is associated with a host name or IP address. - + method queries a DNS server for the IP address that is associated with a host name or IP address. + If an empty string is passed as the `hostNameOrAddress` argument, then this method returns the IPv4 and IPv6 addresses of the local host. - - If the host name could not be found, the exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried. - - The exception is also returned if the `hostNameOrAddress` parameter contains or . - - The method assumes that if an IP literal string is passed in the `hostNameOrAddress` parameter that the application wants an instance returned with all of the properties set. These properties include the , , and . As a result, the implementation of the method exhibits the following behavior when an IP string literal is passed: - -1. The method tries to parse the address. If the `hostNameOrAddress` parameter contains a legal IP string literal, then the first phase succeeds. - -2. A reverse lookup using the IP address of the IP string literal is attempted to obtain the host name. This result is set as the property. - -3. The host name from this reverse lookup is used again to obtain all the possible IP addresses associated with the name and set as the property. - - For an IPv4 string literal, all three steps above may succeed. But it is possible for a stale DNS record for an IPv4 address that actually belongs to a different host to be returned. This may cause step #3 to fail and throw an exception (there is a DNS PTR record for the IPv4 address, but no DNS A record for the IPv4 address). - - For IPv6, step #2 above may fail, since most IPv6 deployments do not register the reverse (PTR) record for an IPv6 address. So this method may return the string IPv6 literal as the fully-qualified domain (FQDN) host name in the property. - - The method has different behavior with respect to IP literals. If step #1 above succeeds (it successfully parses as an IP address), that address is immediately returned as the result. There is no attempt at a reverse lookup. - - IPv6 addresses are filtered from the results of the method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results where available for the `hostNameOrAddress`.parameter. - - The property of the instance returned is not populated by this method and will always be empty. - + + If the host name could not be found, the exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried. + + The exception is also returned if the `hostNameOrAddress` parameter contains or . + + The method assumes that if an IP literal string is passed in the `hostNameOrAddress` parameter that the application wants an instance returned with all of the properties set. These properties include the , , and . As a result, the implementation of the method exhibits the following behavior when an IP string literal is passed: + +1. The method tries to parse the address. If the `hostNameOrAddress` parameter contains a legal IP string literal, then the first phase succeeds. + +2. A reverse lookup using the IP address of the IP string literal is attempted to obtain the host name. This result is set as the property. + +3. The host name from this reverse lookup is used again to obtain all the possible IP addresses associated with the name and set as the property. + + For an IPv4 string literal, all three steps above may succeed. But it is possible for a stale DNS record for an IPv4 address that actually belongs to a different host to be returned. This may cause step #3 to fail and throw an exception (there is a DNS PTR record for the IPv4 address, but no DNS A record for the IPv4 address). + + For IPv6, step #2 above may fail, since most IPv6 deployments do not register the reverse (PTR) record for an IPv6 address. So this method may return the string IPv6 literal as the fully-qualified domain (FQDN) host name in the property. + + The method has different behavior with respect to IP literals. If step #1 above succeeds (it successfully parses as an IP address), that address is immediately returned as the result. There is no attempt at a reverse lookup. + + IPv6 addresses are filtered from the results of the method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results where available for the `hostNameOrAddress`.parameter. + + The property of the instance returned is not populated by this method and will always be empty. + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following example uses the method to resolve an IP address to an instance. - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following example uses the method to resolve an IP address to an instance. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/System.Net.Dns/CPP/dnsnewmethods.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/BeginGetHostEntry/dnsnewmethods.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb" id="Snippet1"::: + ]]> The parameter is . @@ -1464,20 +1466,20 @@ Resolves an IP address to an instance as an asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns an instance that contains address information about the host specified in . - object will complete after the `address` has been resolved. - - This method queries a DNS server for the IP addresses and aliases associated with an IP address. - - IPv6 addresses are filtered from the results of this method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results where available for the `address` parameter. - - The property of the instance returned is not populated by this method and will always be empty. - + object will complete after the `address` has been resolved. + + This method queries a DNS server for the IP addresses and aliases associated with an IP address. + + IPv6 addresses are filtered from the results of this method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results where available for the `address` parameter. + + The property of the instance returned is not populated by this method and will always be empty. + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1528,42 +1530,42 @@ Resolves a host name or IP address to an instance as an asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns an instance that contains address information about the host specified in . - object will complete after the `hostNameOrAddress` has been resolved. - - This method queries a DNS server for the IP address that is associated with a host name or IP address. - + object will complete after the `hostNameOrAddress` has been resolved. + + This method queries a DNS server for the IP address that is associated with a host name or IP address. + If an empty string is passed as the `hostNameOrAddress` argument, then this method returns the IPv4 and IPv6 addresses of the local host. - - If the host name could not be found, the exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried. - - The exception is also returned if the `hostNameOrAddress` parameter contains or . - - This method assumes that if an IP literal string is passed in the `hostNameOrAddress` parameter that the application wants an instance returned with all of the properties set. These properties include the , , and . As a result, the implementation of this method exhibits the following behavior when an IP string literal is passed: - -1. The method tries to parse the address. If the `hostNameOrAddress` parameter contains a legal IP string literal, then the first phase succeeds. - -2. A reverse lookup using the IP address of the IP string literal is attempted to obtain the host name. This result is set as the property. - -3. The host name from this reverse lookup is used again to obtain all the possible IP addresses associated with the name and set as the property. - - For an IPv4 string literal, all three steps above may succeed. But it is possible for a stale DNS record for an IPv4 address that actually belongs to a different host to be returned. This may cause step #3 to fail and throw an exception (there is a DNS PTR record for the IPv4 address, but no DNS A record for the IPv4 address). - - For IPv6, step #2 above may fail, since most IPv6 deployments do not register the reverse (PTR) record for an IPv6 address. So this method may return the string IPv6 literal as the fully-qualified domain (FQDN) host name in the property. - - The method has different behavior with respect to IP literals. If step #1 above succeeds (it successfully parses as an IP address), that address is immediately returned as the result. There is no attempt at a reverse lookup. - - IPv6 addresses are filtered from the results of this method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results where available for the `hostNameOrAddress`.parameter. - - The property of the instance returned is not populated by this method and will always be empty. + + If the host name could not be found, the exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried. + + The exception is also returned if the `hostNameOrAddress` parameter contains or . + + This method assumes that if an IP literal string is passed in the `hostNameOrAddress` parameter that the application wants an instance returned with all of the properties set. These properties include the , , and . As a result, the implementation of this method exhibits the following behavior when an IP string literal is passed: + +1. The method tries to parse the address. If the `hostNameOrAddress` parameter contains a legal IP string literal, then the first phase succeeds. + +2. A reverse lookup using the IP address of the IP string literal is attempted to obtain the host name. This result is set as the property. + +3. The host name from this reverse lookup is used again to obtain all the possible IP addresses associated with the name and set as the property. + + For an IPv4 string literal, all three steps above may succeed. But it is possible for a stale DNS record for an IPv4 address that actually belongs to a different host to be returned. This may cause step #3 to fail and throw an exception (there is a DNS PTR record for the IPv4 address, but no DNS A record for the IPv4 address). + + For IPv6, step #2 above may fail, since most IPv6 deployments do not register the reverse (PTR) record for an IPv6 address. So this method may return the string IPv6 literal as the fully-qualified domain (FQDN) host name in the property. + + The method has different behavior with respect to IP literals. If step #1 above succeeds (it successfully parses as an IP address), that address is immediately returned as the result. There is no attempt at a reverse lookup. + + IPv6 addresses are filtered from the results of this method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty instance if only IPv6 results where available for the `hostNameOrAddress`.parameter. + + The property of the instance returned is not populated by this method and will always be empty. This method is implemented using the underlying operating system's name resolution APIs (such as the Win32 API getaddrinfo on Windows, and equivalent APIs on other platforms). If a host is described in the `hosts` file, the IP address or addresses there will be returned without querying the DNS server. - + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1603,6 +1605,7 @@ Resolves a host name or IP address to an instance as an asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns an instance that contains the address information about the host specified in . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1635,6 +1638,7 @@ Resolves a host name or IP address to an instance as an asynchronous operation. The task object representing the asynchronous operation. The property on the task object returns an instance that contains the address information about the host specified in . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1675,15 +1679,15 @@ Gets the host name of the local computer. A string that contains the DNS host name of the local computer. - method to obtain the host name of the local computer. - + method to obtain the host name of the local computer. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Dns_GetHostName/CPP/dns_gethostname.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/GetHostName/dns_gethostname.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_GetHostName/VB/dns_gethostname.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_GetHostName/VB/dns_gethostname.vb" id="Snippet1"::: + ]]> An error is encountered when resolving the local host name. @@ -1747,27 +1751,27 @@ Resolves a DNS host name or IP address to an instance. An instance that contains address information about the host specified in . - method queries a DNS server for the IP address associated with a host name or IP address. - - When `hostName` is a DNS-style host name associated with multiple IP addresses, only the first IP address that resolves to that host name is returned. - - If the property is set to `true`, the property of the instance returned is not populated by this method and will always be empty. - + method queries a DNS server for the IP address associated with a host name or IP address. + + When `hostName` is a DNS-style host name associated with multiple IP addresses, only the first IP address that resolves to that host name is returned. + + If the property is set to `true`, the property of the instance returned is not populated by this method and will always be empty. + > [!NOTE] -> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). - - - -## Examples - The following example uses the method to resolve an IP address to an instance. - +> This member emits trace information when you enable network tracing in your application. For more information, see [Network Tracing in the .NET Framework](/dotnet/framework/network-programming/network-tracing). + + + +## Examples + The following example uses the method to resolve an IP address to an instance. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Remoting/Dns_Resolve/CPP/dns_resolve.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Net/Dns/Resolve/dns_resolve.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_Resolve/VB/dns_resolve.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Remoting/Dns_Resolve/VB/dns_resolve.vb" id="Snippet1"::: + ]]> diff --git a/xml/System.Runtime.CompilerServices/ConfiguredCancelableAsyncEnumerable`1.xml b/xml/System.Runtime.CompilerServices/ConfiguredCancelableAsyncEnumerable`1.xml index cb8a578c45c..de8138204ed 100644 --- a/xml/System.Runtime.CompilerServices/ConfiguredCancelableAsyncEnumerable`1.xml +++ b/xml/System.Runtime.CompilerServices/ConfiguredCancelableAsyncEnumerable`1.xml @@ -174,6 +174,7 @@ This will replace any previous value set by set by for this iteration. ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Runtime.InteropServices.JavaScript/JSHost.xml b/xml/System.Runtime.InteropServices.JavaScript/JSHost.xml index db6cda2bcef..579a87f1c12 100644 --- a/xml/System.Runtime.InteropServices.JavaScript/JSHost.xml +++ b/xml/System.Runtime.InteropServices.JavaScript/JSHost.xml @@ -93,6 +93,7 @@ If a module with the provided has previously been instantiated, it will be returned instead. A proxy for the JavaScript object that contains the module's exports. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography.Cose/CoseMultiSignMessage.xml b/xml/System.Security.Cryptography.Cose/CoseMultiSignMessage.xml index 33820786b67..26d065c4a5d 100644 --- a/xml/System.Security.Cryptography.Cose/CoseMultiSignMessage.xml +++ b/xml/System.Security.Cryptography.Cose/CoseMultiSignMessage.xml @@ -177,6 +177,7 @@ The header is missing. The content is embedded on this message, use an overload that uses embedded content. + The cancellation token was canceled. This exception is stored into the returned task. @@ -542,6 +543,7 @@ The header is missing. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography.Cose/CoseSign1Message.xml b/xml/System.Security.Cryptography.Cose/CoseSign1Message.xml index 5e5b47ff570..783343b4749 100644 --- a/xml/System.Security.Cryptography.Cose/CoseSign1Message.xml +++ b/xml/System.Security.Cryptography.Cose/CoseSign1Message.xml @@ -219,6 +219,7 @@ The header is missing. + The cancellation token was canceled. This exception is stored into the returned task. @@ -617,6 +618,7 @@ The algorithm protected header was not one of the values supported by this imple The algorithm protected header doesn't match with the algorithms supported by the specified . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography.Cose/CoseSignature.xml b/xml/System.Security.Cryptography.Cose/CoseSignature.xml index 6e4dfc8db14..3371aa8adad 100644 --- a/xml/System.Security.Cryptography.Cose/CoseSignature.xml +++ b/xml/System.Security.Cryptography.Cose/CoseSignature.xml @@ -307,6 +307,7 @@ The algorithm protected header was not one of the values supported by this imple The algorithm protected header doesn't match with the algorithms supported by the specified . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography/CryptoStream.xml b/xml/System.Security.Cryptography/CryptoStream.xml index a95061fd9eb..3c7334b86b3 100644 --- a/xml/System.Security.Cryptography/CryptoStream.xml +++ b/xml/System.Security.Cryptography/CryptoStream.xml @@ -53,14 +53,14 @@ Defines a stream that links data streams to cryptographic transformations. - . Any cryptographic objects that implement can be chained together with any objects that implement , so the streamed output from one object can be fed into the input of another object. The intermediate result (the output from the first object) does not need to be stored separately. > [!IMPORTANT] -> - This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly by calling its method, which in turn calls its implementation. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. +> - This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly by calling its method, which in turn calls its implementation. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. > - When `Stream.Read` or `Stream.ReadAsync` is called with a buffer of length `N`, the operation completes when either: > > - At least one byte has been read from the stream, or @@ -71,12 +71,12 @@ The common language runtime uses a stream-oriented design for cryptography. The Prior to .NET 6, `Stream.Read` and `Stream.ReadAsync` did not return until `N` bytes had been read from the stream or the underlying stream returned 0 from a call to `Read`. If your code assumed they wouldn't return until all `N` bytes were read, it could fail to read all the content. For more information, see [Partial and zero-byte reads in streams](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). You should always explicitly close your object after you are done using it by calling the method. Doing so flushes the underlying stream and causes all remaining blocks of data to be processed by the object. However, if an exception occurs before you call the method, the object might not be closed. To ensure that the method always gets called, place your call to the method within the `finally` block of a `try`/`catch` statement. - -## Examples - The following example demonstrates how to use a to encrypt a string. This method uses class with the specified and initialization vector (). - + +## Examples + The following example demonstrates how to use a to encrypt a string. This method uses class with the specified and initialization vector (). + :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/fileexample.cs" interactive="try-dotnet" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb" id="Snippet1"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb" id="Snippet1"::: ]]> @@ -128,11 +128,11 @@ You should always explicitly close your One of the values. Initializes a new instance of the class with a target data stream, the transformation to use, and the mode of the stream. - can be passed into the `stream` parameter. Any object that implements (such as ) can be passed into the `transform` parameter. - + can be passed into the `stream` parameter. Any object that implements (such as ) can be passed into the `transform` parameter. + ]]> @@ -229,21 +229,21 @@ You should always explicitly close your Begins an asynchronous read operation. (Consider using instead.) An that represents the asynchronous read, which could still be pending. - and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - Pass the `IAsyncResult` return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . You can do this either by using the same code that called `BeginRead` or in a callback passed to `BeginRead`. - - The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. - - Multiple simultaneous asynchronous requests render the request completion order uncertain. - - Use the property to determine whether the current instance supports reading. - - If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginRead`. Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndRead`. - + and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + + Pass the `IAsyncResult` return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . You can do this either by using the same code that called `BeginRead` or in a callback passed to `BeginRead`. + + The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. + + Multiple simultaneous asynchronous requests render the request completion order uncertain. + + Use the property to determine whether the current instance supports reading. + + If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginRead`. Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndRead`. + ]]> Attempted an asynchronous read past the end of the stream, or a disk error occurred. @@ -295,21 +295,21 @@ You should always explicitly close your Begins an asynchronous write operation. (Consider using instead.) An that represents the asynchronous write, which could still be pending. - and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - Pass the `IAsyncResult` returned by the current method to to ensure that the write completes and frees resources appropriately. must be called once for every call to . You can do this either by using the same code that called `BeginWrite` or in a callback passed to `BeginWrite`. If an error occurs during an asynchronous write, an exception will not be thrown until `EndWrite` is called with the `IAsyncResult` returned by this method. - - If a stream is writable, writing at the end of the stream expands the stream. - - The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. - - Use the property to determine whether the current instance supports writing. - - If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginWrite`. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndWrite`. - + and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + + Pass the `IAsyncResult` returned by the current method to to ensure that the write completes and frees resources appropriately. must be called once for every call to . You can do this either by using the same code that called `BeginWrite` or in a callback passed to `BeginWrite`. If an error occurs during an asynchronous write, an exception will not be thrown until `EndWrite` is called with the `IAsyncResult` returned by this method. + + If a stream is writable, writing at the end of the stream expands the stream. + + The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. + + Use the property to determine whether the current instance supports writing. + + If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginWrite`. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndWrite`. + ]]> Attempted an asynchronous write past the end of the stream, or a disk error occurred. @@ -402,11 +402,11 @@ You should always explicitly close your Gets a value indicating whether you can seek within the current . Always . - , so this method always returns `false`. - + , so this method always returns `false`. + ]]> Cryptographic Services @@ -495,13 +495,13 @@ You should always explicitly close your Releases all resources used by the . - implementation. - - Calling `Dispose` allows the resources used by the to be reallocated for other purposes. For more information about `Dispose`, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) - + implementation. + + Calling `Dispose` allows the resources used by the to be reallocated for other purposes. For more information about `Dispose`, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) + ]]> Cryptographic Services @@ -571,22 +571,22 @@ You should always explicitly close your The size, in bytes, of the buffer to use for reading from the underlying stream. This value must be greater than zero. The default size is 81920 bytes. Reads the bytes from the underlying stream, applies the relevant cryptographic transforms, and writes the result to the destination stream. - is . is negative or zero. - The current stream does not support reading. - - -or- - + The current stream does not support reading. + + -or- + does not support writing. Either the current stream or were closed before the method was called. An I/O error occurred. @@ -631,12 +631,12 @@ Copying begins at the current position in the current stream, and does not reset Asynchronously reads the bytes from the underlying stream, applies the relevant cryptographic transforms, and writes the result to the destination stream. A task that represents the asynchronous copy operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -649,6 +649,7 @@ Copying begins at the current position in the current stream, and does not reset The current stream does not support reading, or the destination stream does not support writing. An error occurred during a cryptographic operation. + The cancellation token was canceled. This exception is stored into the returned task. @@ -700,19 +701,19 @@ Copying begins at the current position in the current stream, and does not reset to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method, if it has been overridden. `Dispose()` invokes the protected `Dispose(Boolean)` method with the disposing parameter set to `true`. `Finalize` invokes `Dispose` with disposing set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - + method, if it has been overridden. `Dispose()` invokes the protected `Dispose(Boolean)` method with the disposing parameter set to `true`. `Finalize` invokes `Dispose` with disposing set to `false`. + + When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). Cryptographic Services @@ -749,15 +750,15 @@ Copying begins at the current position in the current stream, and does not reset Asynchronously releases the unmanaged resources used by the . A task that represents the asynchronous dispose operation. - method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - This method disposes the stream by writing any changes to the backing store and closing the stream to release resources. - - Calling `DisposeAsync` allows the resources used by the to be reallocated for other purposes. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). - + method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + + This method disposes the stream by writing any changes to the backing store and closing the stream to release resources. + + Calling `DisposeAsync` allows the resources used by the to be reallocated for other purposes. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). + ]]> @@ -796,25 +797,25 @@ Copying begins at the current position in the current stream, and does not reset Waits for the pending asynchronous read to complete. (Consider using instead.) The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams return zero (0) only at the end of the stream, otherwise, they should block until at least one byte is available. - and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - Call `EndRead` to determine how many bytes were read from the stream. - - `EndRead` can be called once on every from . - - This method blocks until the I/O operation has completed. - + and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + + Call `EndRead` to determine how many bytes were read from the stream. + + `EndRead` can be called once on every from . + + This method blocks until the I/O operation has completed. + ]]> is . - A handle to the pending read operation is not available. - - -or- - + A handle to the pending read operation is not available. + + -or- + The pending operation does not support reading. did not originate from a method on the current stream. @@ -854,23 +855,23 @@ Copying begins at the current position in the current stream, and does not reset A reference to the outstanding asynchronous I/O request. Ends an asynchronous write operation. (Consider using instead.) - and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - `EndWrite` must be called exactly once on every from . - - This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to `EndWrite`. Exceptions thrown by the thread pool thread will not be visible when calling `EndWrite`. - + and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + + `EndWrite` must be called exactly once on every from . + + This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to `EndWrite`. Exceptions thrown by the thread pool thread will not be visible when calling `EndWrite`. + ]]> is . - A handle to the pending write operation is not available. - - -or- - + A handle to the pending write operation is not available. + + -or- + The pending operation does not support writing. did not originate from a method on the current stream. @@ -947,14 +948,14 @@ Copying begins at the current position in the current stream, and does not reset Clears all buffers for the current stream and causes any buffered data to be written to the underlying device. - or . Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. - + or . Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. + > [!NOTE] -> You should call either the method or the method to complete flushing the buffer. - +> You should call either the method or the method to complete flushing the buffer. + ]]> Cryptographic Services @@ -1002,18 +1003,19 @@ Copying begins at the current position in the current stream, and does not reset Clears all buffers for the current stream asynchronously, causes any buffered data to be written to the underlying device, and monitors cancellation requests. A task that represents the asynchronous flush operation. - with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). - - If the operation is canceled before it completes, the returned task contains the value for the property. - + with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). + + If the operation is canceled before it completes, the returned task contains the value for the property. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> The stream has been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1056,18 +1058,18 @@ Copying begins at the current position in the current stream, and does not reset Updates the underlying data source or repository with the current state of the buffer, then clears the buffer. - method will call . If you do not call , call to complete flushing the buffer. Call only when all stream activity is complete. - + method will call . If you do not call , call to complete flushing the buffer. Call only when all stream activity is complete. + ]]> The key is corrupt which can cause invalid padding to the stream. - The current stream is not writable. - - -or- - + The current stream is not writable. + + -or- + The final block has already been transformed. Cryptographic Services @@ -1102,6 +1104,7 @@ Copying begins at the current position in the current stream, and does not reset Asynchronously updates the underlying data source or repository with the current state of the buffer, then clears the buffer. A task that represents the asynchronous flush operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1143,11 +1146,11 @@ Copying begins at the current position in the current stream, and does not reset if the final block has been flushed; otherwise, . - method is called. - + method is called. + ]]> @@ -1192,11 +1195,11 @@ Copying begins at the current position in the current stream, and does not reset Gets the length in bytes of the stream. This property is not supported. - , and cannot be used. - + , and cannot be used. + ]]> This property is not supported. @@ -1243,11 +1246,11 @@ Copying begins at the current position in the current stream, and does not reset Gets or sets the position within the current stream. This property is not supported. - , and cannot be used. - + , and cannot be used. + ]]> This property is not supported. @@ -1310,10 +1313,10 @@ Copying begins at the current position in the current stream, and does not reset The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream has been reached. To be added. The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is write only. - The parameter is less than zero. - - -or- - + The parameter is less than zero. + + -or- + The parameter is less than zero. The sum of the and parameters is longer than the length of the buffer. Cryptographic Services @@ -1355,6 +1358,7 @@ Copying begins at the current position in the current stream, and does not reset To be added. The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is write only. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1405,13 +1409,13 @@ Copying begins at the current position in the current stream, and does not reset Reads a sequence of bytes from the current stream asynchronously, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous read operation. The value of the task object's parameter contains the total number of bytes read into the buffer. The result can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). - - If the operation is canceled before it completes, the returned task contains the value for the property. - + with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). + + If the operation is canceled before it completes, the returned task contains the value for the property. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1425,6 +1429,7 @@ Copying begins at the current position in the current stream, and does not reset The stream has been disposed. The stream is currently in use by a previous read operation. Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1459,13 +1464,13 @@ Copying begins at the current position in the current stream, and does not reset Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. The unsigned byte cast to an , or -1 if at the end of the stream. - property to determine whether the current instance supports reading. - - Attempts to manipulate the stream after the stream has been closed could throw an . - + property to determine whether the current instance supports reading. + + Attempts to manipulate the stream after the stream has been closed could throw an . + ]]> The stream does not support reading. @@ -1518,11 +1523,11 @@ Copying begins at the current position in the current stream, and does not reset Sets the position within the current stream. This method is not supported. - , and cannot be used. - + , and cannot be used. + ]]> This method is not supported. @@ -1572,11 +1577,11 @@ Copying begins at the current position in the current stream, and does not reset The desired length of the current stream in bytes. Sets the length of the current stream. - , and cannot be used. - + , and cannot be used. + ]]> This property exists only to support inheritance from , and cannot be used. @@ -1679,10 +1684,10 @@ This member is an explicit interface member implementation. It can be used only Writes a sequence of bytes to the current and advances the current position within the stream by the number of bytes written. To be added. The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is read only. - The parameter is less than zero. - - -or- - + The parameter is less than zero. + + -or- + The parameter is less than zero. The sum of the and parameters is longer than the length of the buffer. Cryptographic Services @@ -1724,6 +1729,7 @@ This member is an explicit interface member implementation. It can be used only To be added. The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is read only. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1774,13 +1780,13 @@ This member is an explicit interface member implementation. It can be used only Writes a sequence of bytes to the current stream asynchronously, advances the current position within the stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. - with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). - - If the operation is canceled before it completes, the returned task contains the value for the property. - + with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). + + If the operation is canceled before it completes, the returned task contains the value for the property. + This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -1794,6 +1800,7 @@ This member is an explicit interface member implementation. It can be used only The stream has been disposed. The stream is currently in use by a previous write operation. Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1830,11 +1837,11 @@ This member is an explicit interface member implementation. It can be used only The byte to write to the stream. Writes a byte to the current position in the stream and advances the position within the stream by one byte. - property to determine whether the current instance supports writing. - + property to determine whether the current instance supports writing. + ]]> An I/O error occurs. diff --git a/xml/System.Security.Cryptography/HMACMD5.xml b/xml/System.Security.Cryptography/HMACMD5.xml index ad35c37341f..601f253c463 100644 --- a/xml/System.Security.Cryptography/HMACMD5.xml +++ b/xml/System.Security.Cryptography/HMACMD5.xml @@ -54,20 +54,20 @@ Computes a Hash-based Message Authentication Code (HMAC) by using the hash function. - is a type of keyed hash algorithm that is constructed from the Message Digest Algorithm 5 (MD5) hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 128 bits in length. - - An HMAC can be used to determine whether a message sent over an insecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. - - Any change to the data or the hash value results in a mismatch, because knowledge of the secret key is required to change the message and reproduce the correct hash value. Therefore, if the original and computed hash values match, the message is authenticated. - - MD5 is a cryptographic hash algorithm developed at RSA Laboratories. accepts keys of any size, and produces a hash sequence that is 128 bits in length. - - Due to collision problems with MD5, Microsoft recommends SHA256. - - + is a type of keyed hash algorithm that is constructed from the Message Digest Algorithm 5 (MD5) hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 128 bits in length. + + An HMAC can be used to determine whether a message sent over an insecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. + + Any change to the data or the hash value results in a mismatch, because knowledge of the secret key is required to change the message and reproduce the correct hash value. Therefore, if the original and computed hash values match, the message is authenticated. + + MD5 is a cryptographic hash algorithm developed at RSA Laboratories. accepts keys of any size, and produces a hash sequence that is 128 bits in length. + + Due to collision problems with MD5, Microsoft recommends SHA256. + + ]]> Cryptographic Services @@ -128,15 +128,15 @@ Initializes a new instance of the class by using a randomly generated key. - is a type of keyed hash algorithm that is constructed from the MD5 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 128 bits in length. - - This constructor uses a 64-byte, randomly generated key. + is a type of keyed hash algorithm that is constructed from the MD5 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 128 bits in length. + + This constructor uses a 64-byte, randomly generated key. + + Due to collision problems with MD5, Microsoft recommends SHA256. - Due to collision problems with MD5, Microsoft recommends SHA256. - ]]> Cryptographic Services @@ -189,18 +189,18 @@ The secret key for encryption. The key can be any length, but if it is more than 64 bytes long it will be hashed (using SHA-1) to derive a 64-byte key. Therefore, the recommended size of the secret key is 64 bytes. Initializes a new instance of the class by using the specified key. - is a type of keyed hash algorithm that is constructed from the MD5 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 128 bits in length. - - This constructor uses a key you provide to create the object. - - Due to collision problems with MD5, Microsoft recommends SHA256. - -## Examples - For an example of how to use this constructor, see the class. - + is a type of keyed hash algorithm that is constructed from the MD5 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 128 bits in length. + + This constructor uses a key you provide to create the object. + + Due to collision problems with MD5, Microsoft recommends SHA256. + +## Examples + For an example of how to use this constructor, see the class. + ]]> The parameter is . @@ -638,6 +638,7 @@ or is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -683,6 +684,7 @@ is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -738,6 +740,7 @@ does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography/HMACSHA1.xml b/xml/System.Security.Cryptography/HMACSHA1.xml index 38463b9f9be..8bb53d00f87 100644 --- a/xml/System.Security.Cryptography/HMACSHA1.xml +++ b/xml/System.Security.Cryptography/HMACSHA1.xml @@ -61,21 +61,21 @@ Computes a Hash-based Message Authentication Code (HMAC) using the hash function. - is a type of keyed hash algorithm that is constructed from the SHA1 hash function and used as an HMAC, or hash-based message authentication code. The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 160 bits in length. - - An HMAC can be used to determine whether a message sent over an insecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. - - Any change to the data or the hash value results in a mismatch, because knowledge of the secret key is required to change the message and reproduce the correct hash value. Therefore, if the original and computed hash values match, the message is authenticated. - - The SHA-1 (Secure Hash Algorithm, also called SHS, Secure Hash Standard) is a cryptographic hash algorithm published by the United States Government. It produces a 160-bit hash value from an arbitrary length string. - - accepts keys of any size, and produces a hash sequence that is 160 bits in length. - - Due to collision problems with SHA1, Microsoft recommends SHA256. - + is a type of keyed hash algorithm that is constructed from the SHA1 hash function and used as an HMAC, or hash-based message authentication code. The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 160 bits in length. + + An HMAC can be used to determine whether a message sent over an insecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. + + Any change to the data or the hash value results in a mismatch, because knowledge of the secret key is required to change the message and reproduce the correct hash value. Therefore, if the original and computed hash values match, the message is authenticated. + + The SHA-1 (Secure Hash Algorithm, also called SHS, Secure Hash Standard) is a cryptographic hash algorithm published by the United States Government. It produces a 160-bit hash value from an arbitrary length string. + + accepts keys of any size, and produces a hash sequence that is 160 bits in length. + + Due to collision problems with SHA1, Microsoft recommends SHA256. + ]]> Cryptographic Services @@ -131,15 +131,15 @@ Initializes a new instance of the class with a randomly generated key. - is a type of keyed hash algorithm that is constructed from the SHA1 hash function and used as an HMAC, or hash-based message authentication code. The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 160 bits (20 bytes) in length. - - This constructor uses a 64-byte, randomly generated key. + is a type of keyed hash algorithm that is constructed from the SHA1 hash function and used as an HMAC, or hash-based message authentication code. The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 160 bits (20 bytes) in length. + + This constructor uses a 64-byte, randomly generated key. Due to collision problems with SHA1, Microsoft recommends SHA256. - + ]]> Cryptographic Services @@ -247,19 +247,19 @@ The secret key for encryption. The key can be any length, but if it is more than 64 bytes long it is hashed (using SHA-1) to derive a 64-byte key. Therefore, the recommended size of the secret key is 64 bytes. Initializes a new instance of the class with the specified key data. - is a type of keyed hash algorithm that is constructed from the SHA1 hash function and used as an HMAC, or hash-based message authentication code. The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 160 bits (20 bytes) in length. - + is a type of keyed hash algorithm that is constructed from the SHA1 hash function and used as an HMAC, or hash-based message authentication code. The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 160 bits (20 bytes) in length. + > [!NOTE] -> This constructor creates an unmanaged instance of the algorithm by using the class. - -Due to collision problems with SHA1, Microsoft recommends a security model based on SHA256 or better. - -## Examples - For an example of how to use this constructor, see the class. - +> This constructor creates an unmanaged instance of the algorithm by using the class. + +Due to collision problems with SHA1, Microsoft recommends a security model based on SHA256 or better. + +## Examples + For an example of how to use this constructor, see the class. + ]]> The parameter is . @@ -698,6 +698,7 @@ Releases the unmanaged resources used by the or is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -737,6 +738,7 @@ Releases the unmanaged resources used by the is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -786,6 +788,7 @@ Releases the unmanaged resources used by the does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography/HMACSHA256.xml b/xml/System.Security.Cryptography/HMACSHA256.xml index 9d0580e6348..586c49dcbbc 100644 --- a/xml/System.Security.Cryptography/HMACSHA256.xml +++ b/xml/System.Security.Cryptography/HMACSHA256.xml @@ -54,26 +54,26 @@ Computes a Hash-based Message Authentication Code (HMAC) by using the hash function. - is a type of keyed hash algorithm that is constructed from the SHA-256 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 256 bits in length. - - An HMAC can be used to determine whether a message sent over an insecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. - - Any change to the data or the hash value results in a mismatch, because knowledge of the secret key is required to change the message and reproduce the correct hash value. Therefore, if the original and computed hash values match, the message is authenticated. - - accepts keys of any size, and produces a hash sequence 256 bits in length. - - - -## Examples - The following example shows how to sign a file by using the object and then how to verify the file. - + is a type of keyed hash algorithm that is constructed from the SHA-256 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 256 bits in length. + + An HMAC can be used to determine whether a message sent over an insecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. + + Any change to the data or the hash value results in a mismatch, because knowledge of the secret key is required to change the message and reproduce the correct hash value. Therefore, if the original and computed hash values match, the message is authenticated. + + accepts keys of any size, and produces a hash sequence 256 bits in length. + + + +## Examples + The following example shows how to sign a file by using the object and then how to verify the file. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/HMACSHA256/CPP/hmacsha256.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/HMACSHA256/Overview/hmacsha256.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/HMACSHA256/vb/hmacsha256.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/HMACSHA256/vb/hmacsha256.vb" id="Snippet1"::: + ]]> Cryptographic Services @@ -128,13 +128,13 @@ Initializes a new instance of the class with a randomly generated key. - is a type of keyed hash algorithm that is constructed from the SHA-256 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 256 bits in length. - - This constructor uses a 64-byte, randomly generated key. - + is a type of keyed hash algorithm that is constructed from the SHA-256 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 256 bits in length. + + This constructor uses a 64-byte, randomly generated key. + ]]> Cryptographic Services @@ -181,16 +181,16 @@ The secret key for encryption. The key can be any length. However, the recommended size is 64 bytes. If the key is more than 64 bytes long, it is hashed (using SHA-256) to derive a 64-byte key. Initializes a new instance of the class with the specified key data. - is a type of keyed hash algorithm that is constructed from the SHA-256 hash function and used as a Hash-based Message Authentication Code. The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 256 bits in length. - - - -## Examples - For an example of how to use this constructor, see the class. - + is a type of keyed hash algorithm that is constructed from the SHA-256 hash function and used as a Hash-based Message Authentication Code. The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 256 bits in length. + + + +## Examples + For an example of how to use this constructor, see the class. + ]]> The parameter is . @@ -589,6 +589,7 @@ or is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -628,6 +629,7 @@ is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -677,6 +679,7 @@ does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography/HMACSHA384.xml b/xml/System.Security.Cryptography/HMACSHA384.xml index 4ef01a32fde..7b837f68576 100644 --- a/xml/System.Security.Cryptography/HMACSHA384.xml +++ b/xml/System.Security.Cryptography/HMACSHA384.xml @@ -54,26 +54,26 @@ Computes a Hash-based Message Authentication Code (HMAC) using the hash function. - is a type of keyed hash algorithm that is constructed from the SHA-384 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data and hashes the result. The hash value is mixed with the secret key again, and then hashed a second time. The output hash is 384 bits long. - - An HMAC can be used to determine whether a message sent over a nonsecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and the hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. - - If the original and computed hash values match, the message is authenticated. If they do not match, either the data or the hash value has been changed. HMACs provide security against tampering because knowledge of the secret key is required to change the message and reproduce the correct hash value. - - accepts all key sizes and produces a hash sequence that is 384 bits long. - - - -## Examples - The following example shows how to sign a file by using the object, and then how to verify the file. - + is a type of keyed hash algorithm that is constructed from the SHA-384 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data and hashes the result. The hash value is mixed with the secret key again, and then hashed a second time. The output hash is 384 bits long. + + An HMAC can be used to determine whether a message sent over a nonsecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and the hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. + + If the original and computed hash values match, the message is authenticated. If they do not match, either the data or the hash value has been changed. HMACs provide security against tampering because knowledge of the secret key is required to change the message and reproduce the correct hash value. + + accepts all key sizes and produces a hash sequence that is 384 bits long. + + + +## Examples + The following example shows how to sign a file by using the object, and then how to verify the file. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/HMACSHA384/CPP/hmacsha384.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/HMACSHA384/Overview/hmacsha384.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/HMACSHA384/vb/hmacsha384.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/HMACSHA384/vb/hmacsha384.vb" id="Snippet1"::: + ]]> Cryptographic Services @@ -128,11 +128,11 @@ Initializes a new instance of the class by using a randomly generated key. - Cryptographic Services @@ -185,11 +185,11 @@ The secret key for encryption. The key can be any length. However, the recommended size is 128 bytes. If the key is more than 128 bytes long, it is hashed (using SHA-384) to derive a 128-byte key. Initializes a new instance of the class by using the specified key data. - class. - + class. + ]]> The parameter is . @@ -588,6 +588,7 @@ or is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -627,6 +628,7 @@ is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -676,6 +678,7 @@ does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -918,23 +921,23 @@ to enable .NET Framework 2.0 Service Pack 1 applications to interact with .NET Framework 2.0 applications; otherwise, . - Boolean property is to enable .NET Framework 2.0 Service Pack 1 applications to interact with .NET Framework 2.0 applications. When you set this property to `true`, the object produces values that match the values produced by the .NET Framework 2.0. You should set this property only once after you create your HMAC object. You will need to reset your key afterwards, as shown in the following example. - + Boolean property is to enable .NET Framework 2.0 Service Pack 1 applications to interact with .NET Framework 2.0 applications. When you set this property to `true`, the object produces values that match the values produced by the .NET Framework 2.0. You should set this property only once after you create your HMAC object. You will need to reset your key afterwards, as shown in the following example. + ```csharp public static void Test() { - var hmac = new HMACSHA384(); - hmac.ProduceLegacyHmacValues = true; - hmac.Key = // ...Get the HMAC key. - // ... - // Use the HMAC algorithm. + var hmac = new HMACSHA384(); + hmac.ProduceLegacyHmacValues = true; + hmac.Key = // ...Get the HMAC key. // ... -} -``` - + // Use the HMAC algorithm. + // ... +} +``` + ]]> Cryptographic Services diff --git a/xml/System.Security.Cryptography/HMACSHA512.xml b/xml/System.Security.Cryptography/HMACSHA512.xml index 88535b0cb88..3ad40af721f 100644 --- a/xml/System.Security.Cryptography/HMACSHA512.xml +++ b/xml/System.Security.Cryptography/HMACSHA512.xml @@ -54,26 +54,26 @@ Computes a Hash-based Message Authentication Code (HMAC) using the hash function. - is a type of keyed hash algorithm that is constructed from the SHA-512 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data and hashes the result. The hash value is mixed with the secret key again, and then hashed a second time. The output hash is 512 bits in length. - - An HMAC can be used to determine whether a message sent over a nonsecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. - - If the original and computed hash values match, the message is authenticated. If they do not match, either the data or the hash value has been changed. HMACs provide security against tampering because knowledge of the secret key is required to change the message and reproduce the correct hash value. - - accepts keys of any size, and produces a hash sequence of length 512 bits. - - - -## Examples - The following example shows how to sign a file by using the object and then how to verify the file. - + is a type of keyed hash algorithm that is constructed from the SHA-512 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data and hashes the result. The hash value is mixed with the secret key again, and then hashed a second time. The output hash is 512 bits in length. + + An HMAC can be used to determine whether a message sent over a nonsecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC. + + If the original and computed hash values match, the message is authenticated. If they do not match, either the data or the hash value has been changed. HMACs provide security against tampering because knowledge of the secret key is required to change the message and reproduce the correct hash value. + + accepts keys of any size, and produces a hash sequence of length 512 bits. + + + +## Examples + The following example shows how to sign a file by using the object and then how to verify the file. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/HMACSHA512/CPP/hmacsha512.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/HMACSHA512/Overview/hmacsha512.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/HMACSHA512/vb/hmacsha512.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/HMACSHA512/vb/hmacsha512.vb" id="Snippet1"::: + ]]> Cryptographic Services @@ -128,11 +128,11 @@ Initializes a new instance of the class with a randomly generated key. - Cryptographic Services @@ -185,11 +185,11 @@ The secret key for encryption. The key can be any length. However, the recommended size is 128 bytes. If the key is more than 128 bytes long, it is hashed (using SHA-512) to derive a 128-byte key. Initializes a new instance of the class with the specified key data. - class. - + class. + ]]> The parameter is . @@ -588,6 +588,7 @@ or is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -627,6 +628,7 @@ is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -676,6 +678,7 @@ does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -918,23 +921,23 @@ to enable .NET Framework 2.0 Service Pack 1 applications to interact with .NET Framework 2.0 applications; otherwise, . - Boolean property is to enable .NET Framework 2.0 Service Pack 1 applications to interact with .NET Framework 2.0 applications. When you set this property to `true`, the object produces values that match the values produced by the .NET Framework 2.0. You should set this property only once after you create your HMAC object. You will need to reset your key afterwards, as shown in the following example. - + Boolean property is to enable .NET Framework 2.0 Service Pack 1 applications to interact with .NET Framework 2.0 applications. When you set this property to `true`, the object produces values that match the values produced by the .NET Framework 2.0. You should set this property only once after you create your HMAC object. You will need to reset your key afterwards, as shown in the following example. + ```csharp public static void Test() -{ - var hmac = new HMACSHA512(); - hmac.ProduceLegacyHmacValues = true; - hmac.Key = // ...Get the HMAC key. - // ... - // Use the HMAC algorithm. +{ + var hmac = new HMACSHA512(); + hmac.ProduceLegacyHmacValues = true; + hmac.Key = // ...Get the HMAC key. // ... -} -``` - + // Use the HMAC algorithm. + // ... +} +``` + ]]> Cryptographic Services diff --git a/xml/System.Security.Cryptography/HashAlgorithm.xml b/xml/System.Security.Cryptography/HashAlgorithm.xml index 51bc2efa410..18dda6fe2cd 100644 --- a/xml/System.Security.Cryptography/HashAlgorithm.xml +++ b/xml/System.Security.Cryptography/HashAlgorithm.xml @@ -493,6 +493,7 @@ The following example calculates the Asynchronously computes the hash value for the specified object. A task that represents the asynchronous compute hash operation and wraps the computed hash code. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography/MD5.xml b/xml/System.Security.Cryptography/MD5.xml index 777f1fd6c12..6883dac3387 100644 --- a/xml/System.Security.Cryptography/MD5.xml +++ b/xml/System.Security.Cryptography/MD5.xml @@ -55,21 +55,21 @@ Represents the abstract class from which all implementations of the hash algorithm inherit. - algorithm is 128 bits. - - The methods of the class return the hash as an array of 16 bytes. Note that some MD5 implementations produce a 32-character, hexadecimal-formatted hash. To interoperate with such implementations, format the return value of the methods as a hexadecimal value. - + algorithm is 128 bits. + + The methods of the class return the hash as an array of 16 bytes. Note that some MD5 implementations produce a 32-character, hexadecimal-formatted hash. To interoperate with such implementations, format the return value of the methods as a hexadecimal value. + > [!NOTE] -> Due to collision problems with MD5/SHA1, Microsoft recommends SHA256 or SHA512. Consider using the class or the class instead of the class. Use only for compatibility with legacy applications and data. - - - - +> Due to collision problems with MD5/SHA1, Microsoft recommends SHA256 or SHA512. Consider using the class or the class instead of the class. Use only for compatibility with legacy applications and data. + + + + ]]> Cryptographic Services @@ -113,11 +113,11 @@ Initializes a new instance of . - class, use the method. - + class, use the method. + ]]> Cryptographic Services @@ -250,11 +250,11 @@ Creates an instance of the specified implementation of the hash algorithm. A new instance of the specified implementation of . - The algorithm described by the parameter was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible. @@ -516,6 +516,7 @@ is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -569,6 +570,7 @@ does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography/SHA1.xml b/xml/System.Security.Cryptography/SHA1.xml index 27df2958c15..c853a53b30b 100644 --- a/xml/System.Security.Cryptography/SHA1.xml +++ b/xml/System.Security.Cryptography/SHA1.xml @@ -51,16 +51,16 @@ Computes the hash for the input data. - algorithm is 160 bits. - - Due to collision problems with SHA1, Microsoft recommends a security model based on SHA256 or better. - - + algorithm is 160 bits. + + Due to collision problems with SHA1, Microsoft recommends a security model based on SHA256 or better. + + ]]> Cryptographic Services @@ -104,11 +104,11 @@ Initializes a new instance of . - The policy on this object is not compliant with the FIPS algorithm. @@ -176,11 +176,11 @@ Creates an instance of the default implementation of . A new instance of . - is . - + is . + ]]> Cryptographic Services @@ -466,6 +466,7 @@ is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -513,6 +514,7 @@ does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography/SHA256.xml b/xml/System.Security.Cryptography/SHA256.xml index 95e2706896e..f8e1372edfb 100644 --- a/xml/System.Security.Cryptography/SHA256.xml +++ b/xml/System.Security.Cryptography/SHA256.xml @@ -51,22 +51,22 @@ Computes the hash for the input data. - algorithm is 256 bits. - - This is an abstract class. - -## Examples - The following example calculates the SHA-256 hash for all files in a directory. - + algorithm is 256 bits. + + This is an abstract class. + +## Examples + The following example calculates the SHA-256 hash for all files in a directory. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_Classic/classic SHA256 Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/HashAlgorithm/ComputeHash/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic SHA256 Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic SHA256 Example/VB/source.vb" id="Snippet1"::: + ]]> Cryptographic Services @@ -114,11 +114,11 @@ Initializes a new instance of . - Cryptographic Services @@ -248,9 +248,9 @@ Creates an instance of a specified implementation of . A new instance of using the specified implementation. - is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -527,6 +528,7 @@ The .NET Framework includes the implementations and their associated hashName va does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Security.Cryptography/SHA384.xml b/xml/System.Security.Cryptography/SHA384.xml index 748c9013f60..b0950a7cf5b 100644 --- a/xml/System.Security.Cryptography/SHA384.xml +++ b/xml/System.Security.Cryptography/SHA384.xml @@ -51,22 +51,22 @@ Computes the hash for the input data. - algorithm is 384 bits. - - - -## Examples - The following example computes the hash for `data` and stores it in `result`. This example assumes that there is a predefined constant `DATA_SIZE`. - + algorithm is 384 bits. + + + +## Examples + The following example computes the hash for `data` and stores it in `result`. This example assumes that there is a predefined constant `DATA_SIZE`. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_Classic/classic SHA384 Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/SHA384/Overview/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic SHA384 Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic SHA384 Example/VB/source.vb" id="Snippet1"::: + ]]> Cryptographic Services @@ -114,11 +114,11 @@ Initializes a new instance of . - Cryptographic Services @@ -470,6 +470,7 @@ is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -517,6 +518,7 @@ does not support reading.

+ The cancellation token was canceled. This exception is stored into the returned task.
diff --git a/xml/System.Security.Cryptography/SHA512.xml b/xml/System.Security.Cryptography/SHA512.xml index 5c2862a29a4..49f16a4025f 100644 --- a/xml/System.Security.Cryptography/SHA512.xml +++ b/xml/System.Security.Cryptography/SHA512.xml @@ -51,24 +51,24 @@ Computes the hash for the input data. - algorithm is 512 bits. - - This is an abstract class. The only implementation of this class is . - - - -## Examples - The following example computes the hash for `data` and stores it in `result`. This example assumes that there is a predefined constant `DATA_SIZE`. - + algorithm is 512 bits. + + This is an abstract class. The only implementation of this class is . + + + +## Examples + The following example computes the hash for `data` and stores it in `result`. This example assumes that there is a predefined constant `DATA_SIZE`. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_Classic/classic SHA512 Example/CPP/source.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/SHA512/Overview/source.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic SHA512 Example/VB/source.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_Classic/classic SHA512 Example/VB/source.vb" id="Snippet1"::: + ]]> Cryptographic Services @@ -116,11 +116,11 @@ Initializes a new instance of . - Cryptographic Services @@ -249,11 +249,11 @@ Creates an instance of a specified implementation of . A new instance of using the specified implementation. - The algorithm described by the parameter was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible. @@ -479,6 +479,7 @@ is . does not support reading. + The cancellation token was canceled. This exception is stored into the returned task. @@ -526,6 +527,7 @@ does not support reading.

+ The cancellation token was canceled. This exception is stored into the returned task.
diff --git a/xml/System.ServiceModel.Discovery/DiscoveryClient.xml b/xml/System.ServiceModel.Discovery/DiscoveryClient.xml index e5ef6f771e1..fabd1b19ca6 100644 --- a/xml/System.ServiceModel.Discovery/DiscoveryClient.xml +++ b/xml/System.ServiceModel.Discovery/DiscoveryClient.xml @@ -121,11 +121,11 @@ A user specified state object that is passed to the method or one of the methods. It identifies the pending asynchronous operation to cancel. Cancels a pending asynchronous operation. - is thrown if `userState` is `null`. If multiple or operations are called with the same `userState` value, and is called with that `userState` value, an is thrown. - + is thrown if `userState` is `null`. If multiple or operations are called with the same `userState` value, and is called with that `userState` value, an is thrown. + ]]> @@ -276,11 +276,11 @@ The criteria for finding services. Begins an asynchronous find operation with the specified criteria. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -311,11 +311,11 @@ A user specified object to identify the asynchronous find operation. Begins an asynchronous find operation with the specified criteria and user defined state object. - @@ -339,11 +339,11 @@ Occurs when the entire find operation completes. - property contains information about all matching services. For more information about this event, see [Asynchronous Find](/dotnet/framework/wcf/samples/asynchronous-find-sample). - + property contains information about all matching services. For more information about this event, see [Asynchronous Find](/dotnet/framework/wcf/samples/asynchronous-find-sample). + ]]> @@ -367,11 +367,11 @@ Occurs every time the client receives a response from a particular service. - @@ -435,6 +435,7 @@ Begins an asynchronous find task operation with the specified criteria and cancellation token object. An asynchronous find task operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -477,11 +478,11 @@ Opens the . - @@ -569,11 +570,11 @@ The criteria for matching a service endpoint. Begins an asynchronous resolve operation with the specified criteria. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> @@ -604,11 +605,11 @@ A user specified object to identify the asynchronous resolve operation. Begins an asynchronous resolve operation with the specified criteria and user-defined state object. - @@ -693,6 +694,7 @@ Begins an asynchronous resolve task operation with the specified criteria and cancellation token. An asynchronous resolve task operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Text.Json/JsonDocument.xml b/xml/System.Text.Json/JsonDocument.xml index 9a346be30fd..11e6b080bdc 100644 --- a/xml/System.Text.Json/JsonDocument.xml +++ b/xml/System.Text.Json/JsonDocument.xml @@ -25,11 +25,11 @@ Provides a mechanism for examining the structural content of a JSON value without automatically instantiating data values. @@ -305,6 +305,7 @@ The value may be used for the entire lifetime o does not represent a valid single JSON value. contains unsupported options. + The cancellation token was canceled. This exception is stored into the returned task. @@ -339,10 +340,10 @@ The value may be used for the entire lifetime o ## Remarks If the property of `reader` is or , the reader will advance by one call to to determine the start of the value. - + Upon completion of this method, `reader` is positioned at the final token in the JSON value. If an exception is thrown, the reader is reset to the state it was in when the method was called. - + This method makes a copy of the data the reader acted on, so there is no caller requirement to maintain data integrity beyond the return of this method. ]]> @@ -424,12 +425,12 @@ The current token does not start or represent a value ## Remarks If the property of `reader` is or , the reader will advance by one call to to determine the start of the value. - + Upon completion of this method, `reader` is positioned at the final token in the JSON value. If an exception is thrown or `false` is returned, the reader is reset to the state it was in when the method was called. - + This method makes a copy of the data the reader acted on, so there is no caller requirement to maintain data integrity beyond the return of this method. - + ]]> diff --git a/xml/System.Text.Json/JsonSerializer.xml b/xml/System.Text.Json/JsonSerializer.xml index 5249e5e533e..a780c34729f 100644 --- a/xml/System.Text.Json/JsonSerializer.xml +++ b/xml/System.Text.Json/JsonSerializer.xml @@ -1790,6 +1790,7 @@ For more information, see [How to serialize and deserialize JSON](/dotnet/standa There is remaining data in the stream. There is no compatible for or its serializable members. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1827,6 +1828,7 @@ There is remaining data in the stream. The JSON is invalid, the is not compatible with the JSON, or there is remaining data in the Stream. There is no compatible for or its serializable members. The method on the provided did not return a compatible for . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1895,6 +1897,7 @@ There is remaining data in the stream. There is no compatible for or its serializable members. is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1933,6 +1936,7 @@ There is remaining data in the stream. or is . The JSON is invalid, is not compatible with the JSON, or there is remaining data in the Stream. There is no compatible for or its serializable members. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1978,6 +1982,7 @@ There is remaining data in the stream. To be added. is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2012,6 +2017,7 @@ There is remaining data in the stream. To be added. or is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2654,6 +2660,7 @@ For more information, see [How to serialize and deserialize JSON](/dotnet/standa or is . There is no compatible for or its serializable members. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2692,6 +2699,7 @@ For more information, see [How to serialize and deserialize JSON](/dotnet/standa , , or is . There is no compatible for or its serializable members. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2753,6 +2761,7 @@ For more information, see [How to serialize and deserialize JSON](/dotnet/standa is . There is no compatible for or its serializable members. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2791,6 +2800,7 @@ For more information, see [How to serialize and deserialize JSON](/dotnet/standa is . There is no compatible for or its serializable members. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Text.Json/Utf8JsonWriter.xml b/xml/System.Text.Json/Utf8JsonWriter.xml index 09d79a4ad0d..6aae1b88b30 100644 --- a/xml/System.Text.Json/Utf8JsonWriter.xml +++ b/xml/System.Text.Json/Utf8JsonWriter.xml @@ -264,7 +264,7 @@ The instance cannot be reused after dispo ## Remarks In the case of IBufferWriter, this advances the underlying based on what has been written so far. - + In the case of Stream, this writes the data to the stream and flushes it. The instance cannot be reused after disposing. @@ -350,6 +350,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> This instance has been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -924,7 +925,7 @@ The comment value is not escaped before writing. ]]> The specified value is too large. - + -or- contains a comment delimiter (that is, */). @@ -965,7 +966,7 @@ The comment value is not escaped before writing. ]]> The specified value is too large. - + -or- contains a comment delimiter (that is, */). @@ -1006,7 +1007,7 @@ The comment value is not escaped before writing. ]]> The specified value is too large. - + -or- contains a comment delimiter (that is, */). @@ -1271,7 +1272,7 @@ The property name should already be escaped when the instance of The value to be written as a JSON number as part of the name/value pair. Writes a property name specified as a read-only span of bytes and a value (as a JSON number) as part of a name/value pair of a JSON object. - value for the writer instance is honored when using this method. - + The and values for the writer instance are not applied when using this method. ]]> @@ -2972,11 +2973,11 @@ The and value for the writer instance is honored when using this method. - + The and values for the writer instance are not applied when using this method. ]]> @@ -3023,11 +3024,11 @@ The and value for the writer instance is honored when using this method. - + The and values for the writer instance are not applied when using this method. ]]> @@ -3107,7 +3108,7 @@ The property name is escaped before writing. The depth of the JSON exceeds the maximum depth of 1,000. -or- - + Validation is enabled, and this write operation would produce invalid JSON. @@ -3149,7 +3150,7 @@ The property name is escaped before writing. The depth of the JSON exceeds the maximum depth of 1,000. -or- - + Validation is enabled, and this write operation would produce invalid JSON. @@ -3191,7 +3192,7 @@ The property name is escaped before writing. The depth of the JSON exceeds the maximum depth of 1,000. -or- - + Validation is enabled, and this write operation would produce invalid JSON. The parameter is . @@ -3231,7 +3232,7 @@ The property name should already be escaped when the instance of The depth of the JSON has exceeded the maximum depth of 1,000. - + -or- Validation is enabled, and this method would result in writing invalid JSON. @@ -3302,10 +3303,10 @@ The property name is escaped before writing. ]]> The specified property name is too large. - The depth of the JSON exceeds the maximum depth of 1,000. + The depth of the JSON exceeds the maximum depth of 1,000. -or- - + Validation is enabled, and this write operation would produce invalid JSON. @@ -3344,10 +3345,10 @@ The property name is escaped before writing. ]]> The specified property name is too large. - The depth of the JSON exceeds the maximum depth of 1,000. + The depth of the JSON exceeds the maximum depth of 1,000. -or- - + Validation is enabled, and this write operation would produce invalid JSON. @@ -3386,10 +3387,10 @@ The property name is escaped before writing. ]]> The specified property name is too large. - The depth of the JSON exceeds the maximum depth of 1,000. + The depth of the JSON exceeds the maximum depth of 1,000. -or- - + Validation is enabled, and this write operation would produce invalid JSON. The parameter is . @@ -3429,7 +3430,7 @@ The property name should already be escaped when the instance of The depth of the JSON has exceeded the maximum depth of 1,000. - + -or- Validation is enabled, and this method would result in writing invalid JSON. diff --git a/xml/System.Threading.Channels/ChannelReader`1.xml b/xml/System.Threading.Channels/ChannelReader`1.xml index d244127991b..f6429bb4c33 100644 --- a/xml/System.Threading.Channels/ChannelReader`1.xml +++ b/xml/System.Threading.Channels/ChannelReader`1.xml @@ -173,13 +173,14 @@ The created async enumerable. call that returns `true` will read the next item out of the channel. returns `false` once no more data is or will ever be available to read. ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -209,6 +210,7 @@ Each call t Asynchronously reads an item from the channel. A that represents the asynchronous read operation. If the operation is canceled, the operation will not have removed an item from the channel. + The cancellation token was canceled. This exception is stored into the returned task. @@ -314,6 +316,7 @@ Each call t If the channel completes with an exception, the task will also complete with an exception. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Threading.Channels/ChannelWriter`1.xml b/xml/System.Threading.Channels/ChannelWriter`1.xml index 4ea3060f4d8..47086c1fe9e 100644 --- a/xml/System.Threading.Channels/ChannelWriter`1.xml +++ b/xml/System.Threading.Channels/ChannelWriter`1.xml @@ -171,6 +171,7 @@ A that will complete with a result when space is available to write an item or with a result when no further writing will be permitted. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -202,6 +203,7 @@ Asynchronously writes an item to the channel. A that represents the asynchronous write operation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Threading.Tasks.Dataflow/DataflowBlock.xml b/xml/System.Threading.Tasks.Dataflow/DataflowBlock.xml index 80530525174..e547a243d89 100644 --- a/xml/System.Threading.Tasks.Dataflow/DataflowBlock.xml +++ b/xml/System.Threading.Tasks.Dataflow/DataflowBlock.xml @@ -25,11 +25,11 @@ Provides a set of static (Shared in Visual Basic) methods for working with dataflow blocks. - @@ -153,22 +153,22 @@ The second source. The handler to execute on data from the second source. Monitors two dataflow sources, invoking the provided handler for whichever source makes data available first. - A that represents the asynchronous choice. If both sources are completed prior to the choice completing, the resulting task will be canceled. When one of the sources has data available and successfully propagates it to the choice, the resulting task will complete when the handler completes; if the handler throws an exception, the task will end in the state and will contain the unhandled exception. Otherwise, the task will end with its set to either 0 or 1 to represent the first or second source, respectively. - + A that represents the asynchronous choice. If both sources are completed prior to the choice completing, the resulting task will be canceled. When one of the sources has data available and successfully propagates it to the choice, the resulting task will complete when the handler completes; if the handler throws an exception, the task will end in the state and will contain the unhandled exception. Otherwise, the task will end with its set to either 0 or 1 to represent the first or second source, respectively. + This method will only consume an element from one of the two data sources, never both. To be added. - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + The is . @@ -218,22 +218,22 @@ Monitors two dataflow sources, invoking the provided handler for whichever source makes data available first. A that represents the asynchronous choice. If both sources are completed prior to the choice completing, or if the provided as part of is canceled prior to the choice completing, the resulting task will be canceled. When one of the sources has data available and successfully propagates it to the choice, the resulting task will complete when the handler completes; if the handler throws an exception, the task will end in the state and will contain the unhandled exception. Otherwise, the task will end with its set to either 0 or 1 to represent the first or second source, respectively. To be added. - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + The is . @@ -285,30 +285,30 @@ The third source. The handler to execute on data from the third source. Monitors three dataflow sources, invoking the provided handler for whichever source makes data available first. - A that represents the asynchronous choice. If all sources are completed prior to the choice completing, the resulting task will be canceled. When one of the sources has data available and successfully propagates it to the choice, the resulting task will complete when the handler completes; if the handler throws an exception, the task will end in the state and will contain the unhandled exception. Otherwise, the task will end with its set to the 0-based index of the source. - + A that represents the asynchronous choice. If all sources are completed prior to the choice completing, the resulting task will be canceled. When one of the sources has data available and successfully propagates it to the choice, the resulting task will complete when the handler completes; if the handler throws an exception, the task will end in the state and will contain the unhandled exception. Otherwise, the task will end with its set to the 0-based index of the source. + This method will only consume an element from one of the data sources, never more than one. To be added. - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + The is . @@ -362,34 +362,34 @@ The handler to execute on data from the third source. The options with which to configure this choice. Monitors three dataflow sources, invoking the provided handler for whichever source makes data available first. - A that represents the asynchronous choice. If all sources are completed prior to the choice completing, or if the provided as part of is canceled prior to the choice completing, the resulting task will be canceled. When one of the sources has data available and successfully propagates it to the choice, the resulting task will complete when the handler completes; if the handler throws an exception, the task will end in the state and will contain the unhandled exception. Otherwise, the task will end with its set to the 0-based index of the source. - + A that represents the asynchronous choice. If all sources are completed prior to the choice completing, or if the provided as part of is canceled prior to the choice completing, the resulting task will be canceled. When one of the sources has data available and successfully propagates it to the choice, the resulting task will complete when the handler completes; if the handler throws an exception, the task will end in the state and will contain the unhandled exception. Otherwise, the task will end with its set to the 0-based index of the source. + This method will only consume an element from one of the data sources, never more than one. If cancellation is requested after an element has been received, the cancellation request will be ignored, and the relevant handler will be allowed to execute. To be added. - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - - The is . - - -or- - + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + + The is . + + -or- + The is . @@ -433,27 +433,27 @@ Encapsulates a target and a source into a single propagator. The encapsulated target and source. - method requires two existing blocks: a target block (an instance of a class that implements ) and a source block (an instance of a class that implements ). creates a new instance of an internal class that connects the interface members to the `target` parameter and the interface members to the `source` parameter. Both and derive from . Block completion is explicitly passed from sources to targets. Therefore, the and methods are connected to the target while the property is connected to the source. You must ensure that when the target half completes, the source half gets completed in the most appropriate manner; for example: - - `target.Completion.ContinueWith(completion => source.Complete());` - - Or, if you want to propagate the completion type, you can use this more sophisticated code: - -``` -target.Completion.ContinueWith(completion => { if (completion.IsFaulted) - -((IDataflowBlock)batchBlock).Fault(completion.Exception); -else -batchBlock.Complete(); -}); - -``` - - You must also explicitly provide the message propagation from target to source. The benefit of this explicit connection is that it gives you the freedom to perform any unconstrained processing between the two encapsulated blocks. You may do that either by encoding the necessary processing into the blocks' delegates (if the blocks take delegates), or by embedding a sub-network of blocks between them. The easier way is to use a block that takes delegates; for example, use , , (if applicable), or a custom block. - + method requires two existing blocks: a target block (an instance of a class that implements ) and a source block (an instance of a class that implements ). creates a new instance of an internal class that connects the interface members to the `target` parameter and the interface members to the `source` parameter. Both and derive from . Block completion is explicitly passed from sources to targets. Therefore, the and methods are connected to the target while the property is connected to the source. You must ensure that when the target half completes, the source half gets completed in the most appropriate manner; for example: + + `target.Completion.ContinueWith(completion => source.Complete());` + + Or, if you want to propagate the completion type, you can use this more sophisticated code: + +``` +target.Completion.ContinueWith(completion => { if (completion.IsFaulted) + +((IDataflowBlock)batchBlock).Fault(completion.Exception); +else +batchBlock.Complete(); +}); + +``` + + You must also explicitly provide the message propagation from target to source. The benefit of this explicit connection is that it gives you the freedom to perform any unconstrained processing between the two encapsulated blocks. You may do that either by encoding the necessary processing into the blocks' delegates (if the blocks take delegates), or by embedding a sub-network of blocks between them. The easier way is to use a block that takes delegates; for example, use , , (if applicable), or a custom block. + ]]> @@ -496,10 +496,10 @@ batchBlock.Complete(); Links the to the specified . An that, upon calling , will unlink the source from the target. To be added. - The is . - - -or- - + The is . + + -or- + The is . @@ -543,14 +543,14 @@ batchBlock.Complete(); Links the to the specified using the specified filter. An that, upon calling , will unlink the source from the target. To be added. - The is . - - -or- - - The is . - - -or- - + The is . + + -or- + + The is . + + -or- + The is . @@ -596,18 +596,18 @@ batchBlock.Complete(); Links the to the specified using the specified filter. An that, upon calling , will unlink the source from the target. To be added. - The is null (Nothing in Visual Basic). - - -or- - - The is null (Nothing in Visual Basic). - - -or- - - The is null (Nothing in Visual Basic). - - -or- - + The is null (Nothing in Visual Basic). + + -or- + + The is null (Nothing in Visual Basic). + + -or- + + The is null (Nothing in Visual Basic). + + -or- + The is null (Nothing in Visual Basic). @@ -680,8 +680,8 @@ batchBlock.Complete(); Specifies the type of data contained in the source. The source to monitor. Provides a that asynchronously monitors the source for available output. - A that informs of whether and when more output is available. If, when the task completes, its is , more output is available in the source (though another consumer of the source may retrieve the data). - + A that informs of whether and when more output is available. If, when the task completes, its is , more output is available in the source (though another consumer of the source may retrieve the data). + If it returns , more output is not and will never be available, due to the source completing prior to output being available. To be added. @@ -724,6 +724,7 @@ batchBlock.Complete(); Provides a that asynchronously monitors the source for available output. A that informs of whether and when more output is available. If, when the task completes, its is , more output is available in the source (though another consumer of the source may retrieve the data). If it returns , more output is not and will never be available, due to the source completing prior to output being available. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -765,11 +766,11 @@ batchBlock.Complete(); if the item was accepted by the target block; otherwise, . - will return from as soon as it has stored the posted item into its input queue). From the perspective of the block's processing, `Post` is asynchronous. For target blocks that support postponing offered messages, or for blocks that may do more processing in their `Post` implementation, consider using , which will return immediately and will enable the target to postpone the posted message and later consume it after `SendAsync` returns. - + will return from as soon as it has stored the posted item into its input queue). From the perspective of the block's processing, `Post` is asynchronous. For target blocks that support postponing offered messages, or for blocks that may do more processing in their `Post` implementation, consider using , which will return immediately and will enable the target to postpone the posted message and later consume it after `SendAsync` returns. + ]]> @@ -853,11 +854,11 @@ batchBlock.Complete(); Synchronously receives a value from a specified source and provides a token to cancel the operation. The received value. - @@ -904,18 +905,18 @@ batchBlock.Complete(); Synchronously receives a value from a specified source, observing an optional time-out period. The received value. - - is a negative number other than -1 milliseconds, which represents an infinite time-out period. - - -or- - + is a negative number other than -1 milliseconds, which represents an infinite time-out period. + + -or- + is greater than Int32.MaxValue. is . @@ -963,19 +964,19 @@ batchBlock.Complete(); Synchronously receives a value from a specified source, providing a token to cancel the operation and observing an optional time-out interval. The received value. - The is . - is a negative number other than -1 milliseconds, which represents an infinite time-out period. - - -or- - + is a negative number other than -1 milliseconds, which represents an infinite time-out period. + + -or- + is greater than Int32.MaxValue. No item could be received from the source. The specified time-out expired before an item was received from the source. @@ -1012,6 +1013,7 @@ batchBlock.Complete(); The created async enumerable. To be added. The is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1094,6 +1096,7 @@ batchBlock.Complete(); To be added. is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1137,10 +1140,10 @@ batchBlock.Complete(); is . - is a negative number other than -1 milliseconds, which represents an infinite time-out period. - - -or- - + is a negative number other than -1 milliseconds, which represents an infinite time-out period. + + -or- + is greater than Int32.MaxValue. @@ -1187,11 +1190,12 @@ batchBlock.Complete(); is . - is a negative number other than -1 milliseconds, which represents an infinite time-out period. - - -or- - + is a negative number other than -1 milliseconds, which represents an infinite time-out period. + + -or- + is greater than Int32.MaxValue. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1273,11 +1277,12 @@ batchBlock.Complete(); The item being offered to the target. The cancellation token with which to request cancellation of the send operation. Asynchronously offers a message to the target message block, allowing for postponement. - A that represents the asynchronous send. If the target accepts and consumes the offered element during the call to SendAsync, upon return from the call the resulting will be completed and its Result property will return true. If the target declines the offered element during the call, upon return from the call the resulting will be completed and its Result property will return false. If the target postpones the offered element, the element will be buffered until such time that the target consumes or releases it, at which point the Task will complete, with its Result indicating whether the message was consumed. If the target never attempts to consume or release the message, the returned task will never complete. - + A that represents the asynchronous send. If the target accepts and consumes the offered element during the call to SendAsync, upon return from the call the resulting will be completed and its Result property will return true. If the target declines the offered element during the call, upon return from the call the resulting will be completed and its Result property will return false. If the target postpones the offered element, the element will be buffered until such time that the target consumes or releases it, at which point the Task will complete, with its Result indicating whether the message was consumed. If the target never attempts to consume or release the message, the returned task will never complete. + If cancellation is requested before the target has successfully consumed the sent data, the returned task will complete in the Canceled state and the data will no longer be available to the target. To be added. The is null (Nothing in Visual Basic). + The cancellation token was canceled. This exception is stored into the returned task. @@ -1326,13 +1331,13 @@ batchBlock.Complete(); if an item could be received; otherwise, . - diff --git a/xml/System.Threading.Tasks/Parallel.xml b/xml/System.Threading.Tasks/Parallel.xml index e33f2305a58..2ad92d580cd 100644 --- a/xml/System.Threading.Tasks/Parallel.xml +++ b/xml/System.Threading.Tasks/Parallel.xml @@ -37,19 +37,19 @@ Provides support for parallel loops and regions. - class provides library-based data parallel replacements for common operations such as for loops, for each loops, and execution of a set of statements. - - - -## Examples - This example demonstrates several approaches to implementing a parallel loop using multiple language constructs. - + class provides library-based data parallel replacements for common operations such as for loops, for each loops, and execution of a set of statements. + + + +## Examples + This example demonstrates several approaches to implementing a parallel loop using multiple language constructs. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/Overview/parallelintro.cs" id="Snippet07"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelintro.vb" id="Snippet07"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelintro.vb" id="Snippet07"::: + ]]> All public and protected members of are thread-safe and may be used concurrently from multiple threads. @@ -109,35 +109,35 @@ Executes a loop in which iterations may run in parallel and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - value that represents the iteration count. - -- A instance that can be used to break out of the loop prematurely. The object is created by the compiler; it cannot be instantiated in user code. - - Calling the method informs the `for` operation that iterations after the current one don't have to execute. However, all iterations before the current one will still have to be executed if they haven't already. - - Therefore, calling is similar to using a break operation within a conventional `for` loop in a language like C#, but it is not a perfect substitute: For example, there is no guarantee that iterations after the current one will definitely not execute. - - If executing all iterations before the current one is not necessary, use the method instead of using . Calling informs the `for` loop that it may abandon all remaining iterations, regardless of whether they're before or after the current iteration, because all required work will have already been completed. However, as with , there are no guarantees regarding which other iterations will not execute. - - If a loop is ended prematurely, the structure that is returned will contain relevant information about the loop's completion. - - If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. - - - -## Examples - The following example executes up to 100 iterations of a loop in parallel. Each iteration pauses for a random interval from 1 to 1,000 milliseconds. A randomly generated value determines on which iteration of the loop the method is called. As the output from the example shows, no iterations whose index is greater than the property value start after the call to the method. - + value that represents the iteration count. + +- A instance that can be used to break out of the loop prematurely. The object is created by the compiler; it cannot be instantiated in user code. + + Calling the method informs the `for` operation that iterations after the current one don't have to execute. However, all iterations before the current one will still have to be executed if they haven't already. + + Therefore, calling is similar to using a break operation within a conventional `for` loop in a language like C#, but it is not a perfect substitute: For example, there is no guarantee that iterations after the current one will definitely not execute. + + If executing all iterations before the current one is not necessary, use the method instead of using . Calling informs the `for` loop that it may abandon all remaining iterations, regardless of whether they're before or after the current iteration, because all required work will have already been completed. However, as with , there are no guarantees regarding which other iterations will not execute. + + If a loop is ended prematurely, the structure that is returned will contain relevant information about the loop's completion. + + If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. + + + +## Examples + The following example executes up to 100 iterations of a loop in parallel. Each iteration pauses for a random interval from 1 to 1,000 milliseconds. A randomly generated value determines on which iteration of the loop the method is called. As the output from the example shows, no iterations whose index is greater than the property value start after the call to the method. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/For/break1.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallelloopstate/vb/break1.vb" id="Snippet2"::: - - Because iterations of the loop are still likely to be executing when the method is called, each iteration calls the property to check whether another iteration has called the method. If the property value is `true`, the iteration checks the value of the property and, if it is greater than the current iteration's index value, returns immediately. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallelloopstate/vb/break1.vb" id="Snippet2"::: + + Because iterations of the loop are still likely to be executing when the method is called, each iteration calls the property to check whether another iteration has called the method. If the property value is `true`, the iteration checks the value of the property and, if it is greater than the current iteration's index value, returns immediately. + ]]> The argument is . @@ -188,21 +188,21 @@ Executes a loop in which iterations may run in parallel. A structure that contains information about which portion of the loop completed. - ) as a parameter. - - If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. - - - -## Examples - The following example uses the method for 100 invocations of a delegate that generates random byte values and computes their sum. - + ) as a parameter. + + If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. + + + +## Examples + The following example uses the method for 100 invocations of a delegate that generates random byte values and computes their sum. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/For/for1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel.for/vb/for1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel.for/vb/for1.vb" id="Snippet1"::: + ]]> The argument is . @@ -252,21 +252,21 @@ Executes a loop with 64-bit indexes in which iterations may run in parallel and the state of the loop can be monitored and manipulated. A structure that contains information on what portion of the loop completed. - ), and a instance that may be used to break out of the loop prematurely. - - Calling the method informs the `for` operation that iterations after the current one don't have to be executed, but all iterations before the current one do. - - Therefore, calling Break is similar to using a break operation within a conventional `for` loop in a language like C#, but it is not a perfect substitute: For example, there is no guarantee that iterations after the current one will definitely not execute. - - If executing all iterations before the current one is not necessary, use the method instead of using . Calling informs the `for` loop that it may abandon all remaining iterations, regardless of whether they're before or after the current iteration, because all required work will have already been completed. However, as with , there are no guarantees regarding which other iterations will not execute. - - If a loop is ended prematurely, the structure that is returned will contain relevant information about the loop's completion. - - If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. - + ), and a instance that may be used to break out of the loop prematurely. + + Calling the method informs the `for` operation that iterations after the current one don't have to be executed, but all iterations before the current one do. + + Therefore, calling Break is similar to using a break operation within a conventional `for` loop in a language like C#, but it is not a perfect substitute: For example, there is no guarantee that iterations after the current one will definitely not execute. + + If executing all iterations before the current one is not necessary, use the method instead of using . Calling informs the `for` loop that it may abandon all remaining iterations, regardless of whether they're before or after the current iteration, because all required work will have already been completed. However, as with , there are no guarantees regarding which other iterations will not execute. + + If a loop is ended prematurely, the structure that is returned will contain relevant information about the loop's completion. + + If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. + ]]> The argument is . @@ -316,13 +316,13 @@ Executes a loop with 64-bit indexes in which iterations may run in parallel. A structure that contains information about which portion of the loop completed. - ) as a parameter. - - If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. - + ) as a parameter. + + If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. + ]]> The argument is . @@ -374,20 +374,20 @@ Executes a loop in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - ), and a instance that may be used to break out of the loop prematurely. - - If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. - + ), and a instance that may be used to break out of the loop prematurely. + + If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. + ]]> The in the argument is canceled. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. The associated with the in the has been disposed. @@ -438,28 +438,28 @@ Executes a loop in which iterations may run in parallel and loop options can be configured. A structure that contains information about which portion of the loop completed. - ) as a parameter. - - If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. - - - -## Examples - The following example shows how to cancel a parallel loop: - + ) as a parameter. + + If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. + + + +## Examples + The following example shows how to cancel a parallel loop: + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/Overview/parallelforcancel.cs" id="Snippet05"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelforcancel.vb" id="Snippet05"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelforcancel.vb" id="Snippet05"::: + ]]> The in the argument is canceled. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. The associated with the in the has been disposed. @@ -510,28 +510,28 @@ Executes a loop with 64-bit indexes in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - ), and a instance that may be used to break out of the loop prematurely. - - If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. - - - -## Examples - The following example shows how to use the method with a object: - + ), and a instance that may be used to break out of the loop prematurely. + + If `fromInclusive` is greater than or equal to `toExclusive`, the method returns immediately without performing any iterations. + + + +## Examples + The following example shows how to use the method with a object: + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/Overview/parallelfor.cs" id="Snippet03"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelfor.vb" id="Snippet03"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelfor.vb" id="Snippet03"::: + ]]> The in the argument is canceled. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. The associated with the in the has been disposed. @@ -582,28 +582,28 @@ Executes a loop with 64-bit indexes in which iterations may run in parallel and loop options can be configured. A structure that contains information about which portion of the loop completed. - ) as a parameter. - - If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. - - - -## Examples - The following example shows how to use to specify a custom task scheduler: - + ) as a parameter. + + If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. + + + +## Examples + The following example shows how to use to specify a custom task scheduler: + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/Overview/parallelforwithscheduler.cs" id="Snippet06"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelforwithscheduler.vb" id="Snippet06"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelforwithscheduler.vb" id="Snippet06"::: + ]]> The in the argument is canceled. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. The associated with the in the has been disposed. @@ -660,29 +660,29 @@ Executes a loop with thread-local data in which iterations may run in parallel, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - ), a instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread. - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - - If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. - - For an example that uses this method, see [How to: Write a Parallel.For Loop with Thread-Local Variables](/dotnet/standard/parallel-programming/how-to-write-a-parallel-for-loop-with-thread-local-variables). - + ), a instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread. + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + + If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. + + For an example that uses this method, see [How to: Write a Parallel.For Loop with Thread-Local Variables](/dotnet/standard/parallel-programming/how-to-write-a-parallel-for-loop-with-thread-local-variables). + ]]> - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. Parallel Loops @@ -738,29 +738,29 @@ Executes a loop with 64-bit indexes and thread-local data in which iterations may run in parallel, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - ), a instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same task. - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - - If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. - - For an example that uses this method, see [How to: Write a Parallel.For Loop with Thread-Local Variables](/dotnet/standard/parallel-programming/how-to-write-a-parallel-for-loop-with-thread-local-variables). - + ), a instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same task. + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + + If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. + + For an example that uses this method, see [How to: Write a Parallel.For Loop with Thread-Local Variables](/dotnet/standard/parallel-programming/how-to-write-a-parallel-for-loop-with-thread-local-variables). + ]]> - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. Parallel Loops @@ -818,39 +818,39 @@ Executes a loop with thread-local data in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - ), a instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same task. - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple threads; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - - If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. - - - -## Examples - The following example uses thread-local variables to compute the sum of the results of many lengthy operations. This example limits the degree of parallelism to four. - + ), a instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same task. + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple threads; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + + If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. + + + +## Examples + The following example uses thread-local variables to compute the sum of the results of many lengthy operations. This example limits the degree of parallelism to four. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/Overview/threadlocalforwithoptions.cs" id="Snippet04"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/threadlocalforwithoptions.vb" id="Snippet04"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/threadlocalforwithoptions.vb" id="Snippet04"::: + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The in the argument is canceled. The associated with the in the has been disposed. @@ -910,31 +910,31 @@ Executes a loop with 64-bit indexes and thread-local data in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - ), a instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread. - - The `localInit` delegate is invoked once for each thread that participates in the loop's execution and returns the initial local state for each of those threads. These initial states are passed to the first `body` invocations on each thread. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per thread to perform a final action on each thread's local state. This delegate might be invoked concurrently on multiple threads; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - - If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. - + ), a instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread. + + The `localInit` delegate is invoked once for each thread that participates in the loop's execution and returns the initial local state for each of those threads. These initial states are passed to the first `body` invocations on each thread. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per thread to perform a final action on each thread's local state. This delegate might be invoked concurrently on multiple threads; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + + If `fromInclusive` is greater than or equal to `toExclusive`, then the method returns immediately without performing any iterations. + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The in the argument is canceled. The associated with the in the has been disposed. @@ -996,26 +996,26 @@ Executes a ( in Visual Basic) operation on a in which iterations may run in parallel and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - + method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + ]]> - The argument is . - - -or- - + The argument is . + + -or- + The argument is . - The property in the orderable partitioner returns . - - -or- - - The property in the source orderable partitioner returns . - - -or- - + The property in the orderable partitioner returns . + + -or- + + The property in the source orderable partitioner returns . + + -or- + Any methods in the source orderable partitioner return . The exception thrown from one of the specified delegates. Parallel Loops @@ -1065,26 +1065,26 @@ Executes a ( in Visual Basic) operation on a in which iterations may run in parallel, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - + method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + ]]> - The argument is . - - -or- - + The argument is . + + -or- + The argument is . - The property in the partitioner returns . - - -or- - - A method in the partitioner returns . - - -or- - + The property in the partitioner returns . + + -or- + + A method in the partitioner returns . + + -or- + The method in the partitioner does not return the correct number of partitions. Parallel Loops The exception that is thrown to contain an exception thrown from one of the specified delegates. @@ -1134,34 +1134,34 @@ Executes a ( in Visual Basic) operation on a in which iterations may run in parallel. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - - - -## Examples - The following example shows how to implement a range partitioner for use with : - + method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + + + +## Examples + The following example shows how to implement a range partitioner for use with : + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/ForEachTSource/rangepartitioner.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel_rangepartitioners/vb/rangepart.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel_rangepartitioners/vb/rangepart.vb" id="Snippet01"::: + ]]> - The argument is . - - -or- - + The argument is . + + -or- + The argument is . - The property in the partitioner returns . - - -or- - - The exception that is thrown when any methods in the partitioner return . - - -or- - + The property in the partitioner returns . + + -or- + + The exception that is thrown when any methods in the partitioner return . + + -or- + The method in the partitioner does not return the correct number of partitions. Parallel Loops The exception that is thrown to contain an exception thrown from one of the specified delegates. @@ -1211,17 +1211,17 @@ Executes a ( in Visual Basic) operation with 64-bit indexes on an in which iterations may run in parallel, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - instance that may be used to break out of the loop prematurely, and the current element's index (). - + instance that may be used to break out of the loop prematurely, and the current element's index (). + ]]> - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. Parallel Loops @@ -1271,17 +1271,17 @@ Executes a ( in Visual Basic) operation on an in which iterations may run in parallel, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - instance that may be used to break out of the loop prematurely. - + instance that may be used to break out of the loop prematurely. + ]]> - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. Parallel Loops @@ -1331,25 +1331,25 @@ Executes a ( in Visual Basic) operation on an in which iterations may run in parallel. A structure that contains information about which portion of the loop completed. - method to count the number of vowels and non-white-space characters in a text file. In this case, the value returned by the method is ignored. Note that, because operations can run in parallel, you must ensure that incrementing the counter variables is an atomic operation, and that multiple threads do not attempt to access the counter variables simultaneously. For this purpose, the example uses the `lock` statement (in C#) and the `SyncLock` statement (in Visual Basic). - + method to count the number of vowels and non-white-space characters in a text file. In this case, the value returned by the method is ignored. Note that, because operations can run in parallel, you must ensure that incrementing the counter variables is an atomic operation, and that multiple threads do not attempt to access the counter variables simultaneously. For this purpose, the example uses the `lock` statement (in C#) and the `SyncLock` statement (in Visual Basic). + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/ForEachTSource/foreach1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel.foreach/vb/foreach1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel.foreach/vb/foreach1.vb" id="Snippet1"::: + ]]> - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. Parallel Loops @@ -1401,32 +1401,32 @@ Executes a ( in Visual Basic) operation on a in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - + method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + ]]> The in the argument is canceled - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The associated with the in the has been disposed. - The property in the orderable partitioner returns . - - -or- - - The property in the orderable partitioner returns . - - -or- - + The property in the orderable partitioner returns . + + -or- + + The property in the orderable partitioner returns . + + -or- + The exception that is thrown when any methods in the orderable partitioner return . Parallel Loops The exception that is thrown to contain an exception thrown from one of the specified delegates. @@ -1478,28 +1478,28 @@ Executes a ( in Visual Basic) operation on a in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - + method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + ]]> The in the argument is canceled. The associated with the in the has been disposed. - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + The argument is . - The property in the partitioner returns . - - -or- - + The property in the partitioner returns . + + -or- + The exception that is thrown when any methods in the partitioner return . Parallel Loops The exception that is thrown to contain an exception thrown from one of the specified delegates. @@ -1551,28 +1551,28 @@ Executes a ( in Visual Basic) operation on a in which iterations may run in parallel and loop options can be configured. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - + method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + ]]> The in the argument is canceled. The associated with the in the has been disposed. - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + The argument is . - The property in the partitioner returns . - - -or- - + The property in the partitioner returns . + + -or- + The exception that is thrown when any methods in the partitioner return . Parallel Loops The exception that is thrown to contain an exception thrown from one of the specified delegates. @@ -1624,22 +1624,22 @@ Executes a ( in Visual Basic) operation with 64-bit indexes on an in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - instance that may be used to break out of the loop prematurely, and the current element's index (). - + instance that may be used to break out of the loop prematurely, and the current element's index (). + ]]> The in the argument is canceled - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. The associated with the in the has been disposed. @@ -1692,22 +1692,22 @@ Executes a ( in Visual Basic) operation on an in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - instance that may be used to break out of the loop prematurely. - + instance that may be used to break out of the loop prematurely. + ]]> The in the argument is canceled - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. The associated with the in the has been disposed. @@ -1760,22 +1760,22 @@ Executes a ( in Visual Basic) operation on an in which iterations may run in parallel and loop options can be configured. A structure that contains information about which portion of the loop completed. - The in the argument is canceled - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. The associated with the in the has been disposed. @@ -1832,29 +1832,29 @@ Executes a ( in Visual Basic) operation with thread-local data on a in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - + method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The property in the returns or the partitioner returns partitions. The exception that contains all the individual exceptions thrown on all threads. @@ -1911,29 +1911,29 @@ Executes a ( in Visual Basic) operation with thread-local data on a in which iterations may run in parallel and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - - The `localInit` delegate is invoked once for each thread that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - + method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + + The `localInit` delegate is invoked once for each thread that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The property in the returns or the partitioner returns partitions. The exception that contains all the individual exceptions thrown on all threads. @@ -1990,29 +1990,29 @@ Executes a ( in Visual Basic) operation with thread-local data on an in which iterations may run in parallel and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - instance that may be used to break out of the loop prematurely, the current element's index (), and some local state that may be shared amongst iterations that execute on the same thread. - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - + instance that may be used to break out of the loop prematurely, the current element's index (), and some local state that may be shared amongst iterations that execute on the same thread. + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. Parallel Loops @@ -2068,37 +2068,37 @@ Executes a ( in Visual Basic) operation with thread-local data on an in which iterations may run in parallel, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread. - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per thread to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - - - -## Examples - The following example shows how to use a method with local state: - + instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread. + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per thread to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + + + +## Examples + The following example shows how to use a method with local state: + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/Overview/parallelforeach.cs" id="Snippet02"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelforeach.vb" id="Snippet02"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelforeach.vb" id="Snippet02"::: + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The exception that contains all the individual exceptions thrown on all threads. Parallel Loops @@ -2156,29 +2156,29 @@ Executes a ( in Visual Basic) operation with 64-bit indexes and with thread-local data on a in which iterations may run in parallel , loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - + method expects custom partitioners to support dynamic partitioning. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The or argument is . The property in the returns or the partitioner returns partitions. The exception that contains all the individual exceptions thrown on all threads. @@ -2239,33 +2239,33 @@ Executes a ( in Visual Basic) operation with thread-local data on a in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - method expects custom partitioners to support dynamic partitioning. This overload is provided for scenarios with small loop bodies that might benefit from static range partitioning. Partitioners must support dynamic partitions. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - + method expects custom partitioners to support dynamic partitioning. This overload is provided for scenarios with small loop bodies that might benefit from static range partitioning. Partitioners must support dynamic partitions. For more information, see [Custom Partitioners for PLINQ and TPL](/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl) and [How to: Implement Dynamic Partitions](/dotnet/standard/parallel-programming/how-to-implement-dynamic-partitions). + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per task to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The property in the returns or the partitioner returns partitions. The exception that contains all the individual exceptions thrown on all threads. @@ -2326,33 +2326,33 @@ Executes a ( in Visual Basic) operation with thread-local data and 64-bit indexes on an in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - instance that may be used to break out of the loop prematurely, the current element's index (), and some local state that may be shared amongst iterations that execute on the same thread. - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per thread to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - + instance that may be used to break out of the loop prematurely, the current element's index (), and some local state that may be shared amongst iterations that execute on the same thread. + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per thread to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The in the argument is canceled. The associated with the in the has been disposed. @@ -2412,33 +2412,33 @@ Executes a ( in Visual Basic) operation with thread-local data on an in which iterations may run in parallel, loop options can be configured, and the state of the loop can be monitored and manipulated. A structure that contains information about which portion of the loop completed. - instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread. - - The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per thread to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. - - The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. - + instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread. + + The `localInit` delegate is invoked once for each task that participates in the loop's execution and returns the initial local state for each of those tasks. These initial states are passed to the first `body` invocations on each task. Then, every subsequent body invocation returns a possibly modified state value that is passed to the next body invocation. Finally, the last body invocation on each task returns a state value that is passed to the `localFinally` delegate. The `localFinally` delegate is invoked once per thread to perform a final action on each task's local state. This delegate might be invoked concurrently on multiple tasks; therefore, you must synchronize access to any shared variables. + + The method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying object the chance to add, change, or remove threads that service the loop. + ]]> - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The in the argument is canceled. The associated with the in the has been disposed. @@ -2590,6 +2590,7 @@ The operation will execute at most oper or is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2682,6 +2683,7 @@ The operation will execute at most oper or is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2780,23 +2782,23 @@ The operation will execute at most oper An array of to execute. Executes each of the provided actions, possibly in parallel. - method with other methods, anonymous delegates, and lambda expressions. - + method with other methods, anonymous delegates, and lambda expressions. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Parallel/Overview/parallelinvoke.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelinvoke.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.parallel/vb/parallelinvoke.vb" id="Snippet01"::: + ]]> The argument is . @@ -2850,22 +2852,22 @@ The operation will execute at most oper An array of actions to execute. Executes each of the provided actions, possibly in parallel, unless the operation is cancelled by the user. - structure enables the caller to cancel the entire operation. For more information, see [Cancellation in Managed Threads](/dotnet/standard/threading/cancellation-in-managed-threads). - - No guarantees are made about the order in which the operations execute or whether they execute in parallel. This method does not return until each of the provided operations has completed, regardless of whether completion occurs due to normal or exceptional termination. - - For more information, see [How to: Use Parallel.Invoke to Execute Parallel Operations](/dotnet/standard/parallel-programming/how-to-use-parallel-invoke-to-execute-parallel-operations). - + structure enables the caller to cancel the entire operation. For more information, see [Cancellation in Managed Threads](/dotnet/standard/threading/cancellation-in-managed-threads). + + No guarantees are made about the order in which the operations execute or whether they execute in parallel. This method does not return until each of the provided operations has completed, regardless of whether completion occurs due to normal or exceptional termination. + + For more information, see [How to: Use Parallel.Invoke to Execute Parallel Operations](/dotnet/standard/parallel-programming/how-to-use-parallel-invoke-to-execute-parallel-operations). + ]]> The in the is set. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The exception that is thrown when any action in the array throws an exception. The array contains a element. diff --git a/xml/System.Threading.Tasks/Task.xml b/xml/System.Threading.Tasks/Task.xml index 121dbfdc3c8..31f2d856eee 100644 --- a/xml/System.Threading.Tasks/Task.xml +++ b/xml/System.Threading.Tasks/Task.xml @@ -71,103 +71,103 @@ Represents an asynchronous operation. - class represents a single operation that does not return a value and that usually executes asynchronously. objects are one of the central components of the [task-based asynchronous pattern](/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap) first introduced in the .NET Framework 4. Because the work performed by a object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the property, as well as the , , and properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform. - - For operations that return values, you use the class. - - In this section: - - [Task instantiation examples](#Instant) - [Creating and executing a task](#Creating) - [Separating task creation and execution](#Separating) - [Waiting for one or more tasks to complete](#WaitingForOne) - [Tasks and culture](#Culture) - [For debugger developers](#Debugger) - - -## Task instantiation - The following example creates and executes four tasks. Three tasks execute an delegate named `action`, which accepts an argument of type . A fourth task executes a lambda expression (an delegate) that is defined inline in the call to the task creation method. Each task is instantiated and run in a different way: - -- Task `t1` is instantiated by calling a Task class constructor, but is started by calling its method only after task `t2` has started. - -- Task `t2` is instantiated and started in a single method call by calling the method. - -- Task `t3` is instantiated and started in a single method call by calling the method. - -- Task `t4` is executed synchronously on the main thread by calling the method. - - Because task `t4` executes synchronously, it executes on the main application thread. The remaining tasks execute asynchronously typically on one or more thread pool threads. - + class represents a single operation that does not return a value and that usually executes asynchronously. objects are one of the central components of the [task-based asynchronous pattern](/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap) first introduced in the .NET Framework 4. Because the work performed by a object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the property, as well as the , , and properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform. + + For operations that return values, you use the class. + + In this section: + + [Task instantiation examples](#Instant) + [Creating and executing a task](#Creating) + [Separating task creation and execution](#Separating) + [Waiting for one or more tasks to complete](#WaitingForOne) + [Tasks and culture](#Culture) + [For debugger developers](#Debugger) + + +## Task instantiation + The following example creates and executes four tasks. Three tasks execute an delegate named `action`, which accepts an argument of type . A fourth task executes a lambda expression (an delegate) that is defined inline in the call to the task creation method. Each task is instantiated and run in a different way: + +- Task `t1` is instantiated by calling a Task class constructor, but is started by calling its method only after task `t2` has started. + +- Task `t2` is instantiated and started in a single method call by calling the method. + +- Task `t3` is instantiated and started in a single method call by calling the method. + +- Task `t4` is executed synchronously on the main thread by calling the method. + + Because task `t4` executes synchronously, it executes on the main application thread. The remaining tasks execute asynchronously typically on one or more thread pool threads. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/startnew.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/startnew.vb" id="Snippet01"::: - - -## Creating and executing a task - instances may be created in a variety of ways. The most common approach, which is available starting with the .NET Framework 4.5, is to call the static method. The method provides a simple way to start a task using default values and without requiring additional parameters. The following example uses the method to start a task that loops and then displays the number of loop iterations: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/startnew.vb" id="Snippet01"::: + + +## Creating and executing a task + instances may be created in a variety of ways. The most common approach, which is available starting with the .NET Framework 4.5, is to call the static method. The method provides a simple way to start a task using default values and without requiring additional parameters. The following example uses the method to start a task that loops and then displays the number of loop iterations: + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/run1.cs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/run1.vb" id="Snippet6"::: - - An alternative, and the most common method to start a task in .NET Framework 4, is the static method. The property returns a object. Overloads of the method let you specify parameters to pass to the task creation options and a task scheduler. The following example uses the method to start a task. It is functionally equivalent to the code in the previous example. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/run1.vb" id="Snippet6"::: + + An alternative, and the most common method to start a task in .NET Framework 4, is the static method. The property returns a object. Overloads of the method let you specify parameters to pass to the task creation options and a task scheduler. The following example uses the method to start a task. It is functionally equivalent to the code in the previous example. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/startnew1.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/startnew1.vb" id="Snippet7"::: - - For more complete examples, see [Task-based Asynchronous Programming](/dotnet/standard/parallel-programming/task-based-asynchronous-programming). - - -## Separating task creation and execution - The class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the or method is the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, you can use the constructors and then call the method to schedule the task for execution at a later time. - - -## Waiting for one or more tasks to complete - Because tasks typically run asynchronously on a thread pool thread, the thread that creates and starts the task continues execution as soon as the task has been instantiated. In some cases, when the calling thread is the main application thread, the app may terminate before the task actually begins execution. In others, your application's logic may require that the calling thread continue execution only when one or more tasks have completed execution. You can synchronize the execution of the calling thread and the asynchronous tasks it launches by calling a `Wait` method to wait for one or more tasks to complete. - - To wait for a single task to complete, you can call its method. A call to the method blocks the calling thread until the single class instance has completed execution. - - The following example calls the parameterless method to wait unconditionally until a task completes. The task simulates work by calling the method to sleep for two seconds. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/startnew1.vb" id="Snippet7"::: + + For more complete examples, see [Task-based Asynchronous Programming](/dotnet/standard/parallel-programming/task-based-asynchronous-programming). + + +## Separating task creation and execution + The class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the or method is the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, you can use the constructors and then call the method to schedule the task for execution at a later time. + + +## Waiting for one or more tasks to complete + Because tasks typically run asynchronously on a thread pool thread, the thread that creates and starts the task continues execution as soon as the task has been instantiated. In some cases, when the calling thread is the main application thread, the app may terminate before the task actually begins execution. In others, your application's logic may require that the calling thread continue execution only when one or more tasks have completed execution. You can synchronize the execution of the calling thread and the asynchronous tasks it launches by calling a `Wait` method to wait for one or more tasks to complete. + + To wait for a single task to complete, you can call its method. A call to the method blocks the calling thread until the single class instance has completed execution. + + The following example calls the parameterless method to wait unconditionally until a task completes. The task simulates work by calling the method to sleep for two seconds. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/Wait1.cs" id="Snippet8"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/Wait1.vb" id="Snippet8"::: - - You can also conditionally wait for a task to complete. The and methods block the calling thread until the task finishes or a timeout interval elapses, whichever comes first. Since the following example launches a task that sleeps for two seconds but defines a one-second timeout value, the calling thread blocks until the timeout expires and before the task has completed execution. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/Wait1.vb" id="Snippet8"::: + + You can also conditionally wait for a task to complete. The and methods block the calling thread until the task finishes or a timeout interval elapses, whichever comes first. Since the following example launches a task that sleeps for two seconds but defines a one-second timeout value, the calling thread blocks until the timeout expires and before the task has completed execution. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/Wait2.cs" id="Snippet9"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/Wait2.vb" id="Snippet9"::: - - You can also supply a cancellation token by calling the and methods. If the token's property is `true` or becomes `true` while the method is executing, the method throws an . - - In some cases, you may want to wait for the first of a series of executing tasks to complete, but don't care which task it is. For this purpose, you can call one of the overloads of the method. The following example creates three tasks, each of which sleeps for an interval determined by a random number generator. The method waits for the first task to complete. The example then displays information about the status of all three tasks. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/Wait2.vb" id="Snippet9"::: + + You can also supply a cancellation token by calling the and methods. If the token's property is `true` or becomes `true` while the method is executing, the method throws an . + + In some cases, you may want to wait for the first of a series of executing tasks to complete, but don't care which task it is. For this purpose, you can call one of the overloads of the method. The following example creates three tasks, each of which sleeps for an interval determined by a random number generator. The method waits for the first task to complete. The example then displays information about the status of all three tasks. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/WhenAny1.cs" id="Snippet10"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/WaitAny1.vb" id="Snippet10"::: - - You can also wait for all of a series of tasks to complete by calling the method. The following example creates ten tasks, waits for all ten to complete, and then displays their status. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/WaitAny1.vb" id="Snippet10"::: + + You can also wait for all of a series of tasks to complete by calling the method. The following example creates ten tasks, waits for all ten to complete, and then displays their status. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/WaitAll1.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/WaitAll1.vb" id="Snippet11"::: - - Note that when you wait for one or more tasks to complete, any exceptions thrown in the running tasks are propagated on the thread that calls the `Wait` method, as the following example shows. It launches 12 tasks, three of which complete normally and three of which throw an exception. Of the remaining six tasks, three are cancelled before they start, and three are cancelled while they are executing. Exceptions are thrown in the method call and are handled by a `try`/`catch` block. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/WaitAll1.vb" id="Snippet11"::: + + Note that when you wait for one or more tasks to complete, any exceptions thrown in the running tasks are propagated on the thread that calls the `Wait` method, as the following example shows. It launches 12 tasks, three of which complete normally and three of which throw an exception. Of the remaining six tasks, three are cancelled before they start, and three are cancelled while they are executing. Exceptions are thrown in the method call and are handled by a `try`/`catch` block. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/WaitAll2.cs" id="Snippet12"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/WaitAll2.vb" id="Snippet12"::: - - For more information on exception handling in task-based asynchronous operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). - - -## Tasks and culture - Starting with desktop apps that target the .NET Framework 4.6, the culture of the thread that creates and invokes a task becomes part of the thread's context. That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. For apps that target versions of the .NET Framework prior to the .NET Framework 4.6, the culture of the task is the culture of the thread on which the task executes. For more information, see the "Culture and task-based asynchronous operations" section in the topic. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/WaitAll2.vb" id="Snippet12"::: + + For more information on exception handling in task-based asynchronous operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). + + +## Tasks and culture + Starting with desktop apps that target the .NET Framework 4.6, the culture of the thread that creates and invokes a task becomes part of the thread's context. That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. For apps that target versions of the .NET Framework prior to the .NET Framework 4.6, the culture of the task is the culture of the thread on which the task executes. For more information, see the "Culture and task-based asynchronous operations" section in the topic. + > [!NOTE] -> Store apps follow the Windows Runtime in setting and getting the default culture. - - -## For debugger developers - For developers implementing custom debuggers, several internal and private members of task may be useful (these may change from release to release). The `m_taskId` field serves as the backing store for the property, however accessing this field directly from a debugger may be more efficient than accessing the same value through the property's getter method (the `s_taskIdCounter` counter is used to retrieve the next available ID for a task). Similarly, the `m_stateFlags` field stores information about the current lifecycle stage of the task, information also accessible through the property. The `m_action` field stores a reference to the task's delegate, and the `m_stateObject` field stores the async state passed to the task by the developer. Finally, for debuggers that parse stack frames, the `InternalWait` method serves a potential marker for when a task is entering a wait operation. - +> Store apps follow the Windows Runtime in setting and getting the default culture. + + +## For debugger developers + For developers implementing custom debuggers, several internal and private members of task may be useful (these may change from release to release). The `m_taskId` field serves as the backing store for the property, however accessing this field directly from a debugger may be more efficient than accessing the same value through the property's getter method (the `s_taskIdCounter` counter is used to retrieve the next available ID for a task). Similarly, the `m_stateFlags` field stores information about the current lifecycle stage of the task, information also accessible through the property. The `m_action` field stores a reference to the task's delegate, and the `m_stateObject` field stores the async state passed to the task by the developer. Finally, for debuggers that parse stack frames, the `InternalWait` method serves a potential marker for when a task is entering a wait operation. + ]]> All members of , except for , are thread-safe and may be used from multiple threads concurrently. @@ -227,26 +227,26 @@ The delegate that represents the code to execute in the task. Initializes a new with the specified action. - object and launch a task is by calling the static or method. - + object and launch a task is by calling the static or method. + If a task with no action is needed just for the consumer of an API to have something to await, a should be used. - -## Examples - The following example uses the constructor to create tasks that retrieve the filenames in specified directories. All tasks write the file names to a single object. The example then calls the method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the object. - + +## Examples + The following example uses the constructor to create tasks that retrieve the filenames in specified directories. All tasks write the file names to a single object. The example then calls the method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the object. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/ctor1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/ctor1.vb" id="Snippet1"::: - - The following example is identical, except that it used the method to instantiate and run the task in a single operation. The method returns the object that represents the task. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/ctor1.vb" id="Snippet1"::: + + The following example is identical, except that it used the method to instantiate and run the task in a single operation. The method returns the object that represents the task. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run2.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run2.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run2.vb" id="Snippet1"::: + ]]> The argument is . @@ -294,23 +294,24 @@ The that the new task will observe. Initializes a new with the specified action and . - object and launch a task is by calling the static and methods. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static and methods. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + For more information, see [Task Parallelism (Task Parallel Library)](/dotnet/standard/parallel-programming/task-based-asynchronous-programming) and [Cancellation in Managed Threads](/dotnet/standard/threading/cancellation-in-managed-threads). - -## Examples - The following example calls the constructor to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the method to add information about each file to a object. Each detached nested task invoked by the loop checks the state of the cancellation token and, if cancellation is requested, calls the method. The method throws an exception that is handled in a `catch` block when the calling thread calls the method. The method is then called to start the task. - + +## Examples + The following example calls the constructor to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the method to add information about each file to a object. Each detached nested task invoked by the loop checks the state of the cancellation token and, if cancellation is requested, calls the method. The method throws an exception that is handled in a `catch` block when the calling thread calls the method. The method is then called to start the task. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run4.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/run4.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/run4.vb" id="Snippet4"::: + ]]> The provided has already been disposed. The argument is null. + The cancellation token was canceled. This exception is stored into the returned task. @@ -354,11 +355,11 @@ The used to customize the task's behavior. Initializes a new with the specified action and creation options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The argument is null. @@ -407,17 +408,17 @@ An object representing data to be used by the action. Initializes a new with the specified action and state. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. -## Examples - The following example defines an array of 6-letter words. Each word is then passed as an argument to the constructor, whose delegate scrambles the characters in the word, then displays the original word and its scrambled version. - +## Examples + The following example defines an array of 6-letter words. Each word is then passed as an argument to the constructor, whose delegate scrambles the characters in the word, then displays the original word and its scrambled version. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/startnew3.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/startnew3.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/startnew3.vb" id="Snippet3"::: + ]]> The argument is null. @@ -467,18 +468,19 @@ The used to customize the task's behavior. Initializes a new with the specified action and creation options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - - For more information, see [Task Parallelism (Task Parallel Library)](/dotnet/standard/parallel-programming/task-based-asynchronous-programming) and [Task Cancellation](/dotnet/standard/parallel-programming/task-cancellation). - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + + For more information, see [Task Parallelism (Task Parallel Library)](/dotnet/standard/parallel-programming/task-based-asynchronous-programming) and [Task Cancellation](/dotnet/standard/parallel-programming/task-cancellation). + ]]> The that created has already been disposed. The argument is null. The argument specifies an invalid value for . + The cancellation token was canceled. This exception is stored into the returned task. @@ -525,15 +527,16 @@ The that the new task will observe. Initializes a new with the specified action, state, and options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The that created has already been disposed. The argument is null. + The cancellation token was canceled. This exception is stored into the returned task. @@ -580,11 +583,11 @@ The used to customize the task's behavior. Initializes a new with the specified action, state, and options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The argument is null. @@ -637,16 +640,17 @@ The used to customize the task's behavior. Initializes a new with the specified action, state, and options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The that created has already been disposed. The argument is null. The argument specifies an invalid value for . + The cancellation token was canceled. This exception is stored into the returned task. @@ -692,12 +696,12 @@ Gets the state object supplied when the was created, or null if none was supplied. An that represents the state data that was passed in to the task when it was created. - @@ -740,13 +744,13 @@ To retrieve the object's data, cast it back to the original type. Gets a task that has already completed successfully. The successfully completed task. - property is set to . To create a task that returns a value and runs to completion, call the method. - - Repeated attempts to retrieve this property value may not always return the same instance. - + property is set to . To create a task that returns a value and runs to completion, call the method. + + Repeated attempts to retrieve this property value may not always return the same instance. + ]]> @@ -866,23 +870,23 @@ When an asynchronous method awaits a directly Creates a continuation that executes asynchronously when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - - - -## Examples - The following example defines a task that populates an array with 100 random date and time values. It uses the method to select the earliest and the latest date values once the array is fully populated. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + + + +## Examples + The following example defines a task that populates an array with 100 random date and time values. It uses the method to select the earliest and the latest date values once the array is fully populated. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/ContinueWith/continuewith1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.continuewith/vb/continuewith1.vb" id="Snippet1"::: - - Because a console application may terminate before the continuation task executes, the method is called to ensure that the continuation finishes executing before the example ends. - - For an additional example, see [Chaining Tasks by Using Continuation Tasks](/dotnet/standard/parallel-programming/chaining-tasks-by-using-continuation-tasks). - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.continuewith/vb/continuewith1.vb" id="Snippet1"::: + + Because a console application may terminate before the continuation task executes, the method is called to ensure that the continuation finishes executing before the example ends. + + For an additional example, see [Chaining Tasks by Using Continuation Tasks](/dotnet/standard/parallel-programming/chaining-tasks-by-using-continuation-tasks). + ]]> The argument is . @@ -934,11 +938,11 @@ When an asynchronous method awaits a directly Creates a continuation that receives caller-supplied state information and executes when the target completes. A new continuation task. - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting early due to cancellation. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting early due to cancellation. + ]]> The argument is . @@ -989,15 +993,16 @@ When an asynchronous method awaits a directly Creates a continuation that receives a cancellation token and executes asynchronously when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The that created the token has already been disposed. The argument is null. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1045,57 +1050,57 @@ When an asynchronous method awaits a directly Creates a continuation that executes when the target task completes according to the specified . A new continuation . - will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - - - -## Examples - The following example demonstrates using to specify that a continuation task should run synchronously when the antecedent task completes. (If the specified task has already completed by the time is called, the synchronous continuation will run on the thread calling .) - -```csharp - -public class TaskCounter -{ - private volatile int _count; - - public void Track(Task t) - { - if (t == null) throw new ArgumentNullException("t"); - Interlocked.Increment(ref _count); - t.ContinueWith(ct => Interlocked.Decrement(ref _count), TaskContinuationOptions.ExecuteSynchronously); - } - - public int NumberOfActiveTasks { get { return _count; } } -} - -``` - -```vb - -Public Class TaskCounter - Private _count as Integer - - Public Sub Track(ByVal t as Task) - If t is Nothing Then Throw New ArgumentNullException("t") - Interlocked.Increment(_count) - t.ContinueWith(Sub(ct) - Interlocked.Decrement(_count) - End Sub, - TaskContinuationOptions.ExecuteSynchronously) - End Sub - - Public ReadOnly Property NumberOfActiveTasks As Integer - Get - Return _count - End Get - End Property -End Class - -``` - + will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + + + +## Examples + The following example demonstrates using to specify that a continuation task should run synchronously when the antecedent task completes. (If the specified task has already completed by the time is called, the synchronous continuation will run on the thread calling .) + +```csharp + +public class TaskCounter +{ + private volatile int _count; + + public void Track(Task t) + { + if (t == null) throw new ArgumentNullException("t"); + Interlocked.Increment(ref _count); + t.ContinueWith(ct => Interlocked.Decrement(ref _count), TaskContinuationOptions.ExecuteSynchronously); + } + + public int NumberOfActiveTasks { get { return _count; } } +} + +``` + +```vb + +Public Class TaskCounter + Private _count as Integer + + Public Sub Track(ByVal t as Task) + If t is Nothing Then Throw New ArgumentNullException("t") + Interlocked.Increment(_count) + t.ContinueWith(Sub(ct) + Interlocked.Decrement(_count) + End Sub, + TaskContinuationOptions.ExecuteSynchronously) + End Sub + + Public ReadOnly Property NumberOfActiveTasks As Integer + Get + Return _count + End Get + End Property +End Class + +``` + ]]> The argument is null. @@ -1147,18 +1152,18 @@ End Class Creates a continuation that executes asynchronously when the target completes. The continuation uses a specified scheduler. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The has been disposed. - The argument is . - - -or- - + The argument is . + + -or- + The argument is null. @@ -1210,15 +1215,16 @@ End Class Creates a continuation that receives caller-supplied state information and a cancellation token and that executes asynchronously when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The argument is . The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1269,11 +1275,11 @@ End Class Creates a continuation that receives caller-supplied state information and executes when the target completes. The continuation executes based on a set of specified conditions. A new continuation . - will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - + will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + ]]> The argument is . @@ -1328,11 +1334,11 @@ End Class Creates a continuation that receives caller-supplied state information and executes asynchronously when the target completes. The continuation uses a specified scheduler. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The argument is . @@ -1387,61 +1393,62 @@ End Class Creates a continuation that executes when the target task competes according to the specified . The continuation receives a cancellation token and uses a specified scheduler. A new continuation . - will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - - - -## Examples - The following is an example of using ContinueWith to run work both in the background and on the user interface threads. - -```csharp - -private void Button1_Click(object sender, EventArgs e) -{ - var backgroundScheduler = TaskScheduler.Default; - var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); - Task.Factory.StartNew(delegate { DoBackgroundComputation(); }, - backgroundScheduler). - ContinueWith(delegate { UpdateUI(); }, uiScheduler). - ContinueWith(delegate { DoAnotherBackgroundComputation(); }, - backgroundScheduler). - ContinueWith(delegate { UpdateUIAgain(); }, uiScheduler); -} - -``` - -```vb - -Private Sub Button1_Click(ByVal sender As System.Object, - ByVal e As System.EventArgs) Handles Button1.Click - Dim backgroundScheduler = TaskScheduler.Default - Dim uiScheduler = TaskScheduler.FromCurrentSynchronizationContext() - - Task.Factory.StartNew(Sub() - DoBackgroundComputation() - End Sub, backgroundScheduler).ContinueWith(Sub(t) - UpdateUI() - End Sub, uiScheduler).ContinueWith(Sub(t) - DoAnotherBackgroundComputation() - End Sub, backgroundScheduler).ContinueWith(Sub(t) - UpdateUIAgain() - End Sub, uiScheduler) -End Sub - -``` - + will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + + + +## Examples + The following is an example of using ContinueWith to run work both in the background and on the user interface threads. + +```csharp + +private void Button1_Click(object sender, EventArgs e) +{ + var backgroundScheduler = TaskScheduler.Default; + var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); + Task.Factory.StartNew(delegate { DoBackgroundComputation(); }, + backgroundScheduler). + ContinueWith(delegate { UpdateUI(); }, uiScheduler). + ContinueWith(delegate { DoAnotherBackgroundComputation(); }, + backgroundScheduler). + ContinueWith(delegate { UpdateUIAgain(); }, uiScheduler); +} + +``` + +```vb + +Private Sub Button1_Click(ByVal sender As System.Object, + ByVal e As System.EventArgs) Handles Button1.Click + Dim backgroundScheduler = TaskScheduler.Default + Dim uiScheduler = TaskScheduler.FromCurrentSynchronizationContext() + + Task.Factory.StartNew(Sub() + DoBackgroundComputation() + End Sub, backgroundScheduler).ContinueWith(Sub(t) + UpdateUI() + End Sub, uiScheduler).ContinueWith(Sub(t) + DoAnotherBackgroundComputation() + End Sub, backgroundScheduler).ContinueWith(Sub(t) + UpdateUIAgain() + End Sub, uiScheduler) +End Sub + +``` + ]]> The that created the token has already been disposed. - The argument is null. - - -or- - + The argument is null. + + -or- + The argument is null. The argument specifies an invalid value for . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1496,16 +1503,17 @@ End Sub Creates a continuation that receives caller-supplied state information and a cancellation token and that executes when the target completes. The continuation executes based on a set of specified conditions and uses a specified scheduler. A new continuation . - will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - + will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + ]]> The argument is . The argument specifies an invalid value for . The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1555,19 +1563,19 @@ End Sub Creates a continuation that executes asynchronously when the target completes and returns a value. A new continuation task. - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - - - -## Examples - The following example shows how to use the ContinueWith method: - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + + + +## Examples + The following example shows how to use the ContinueWith method: + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/continuationsimple.cs" id="Snippet03"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/continuationsimple.vb" id="Snippet03"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/continuationsimple.vb" id="Snippet03"::: + ]]> The has been disposed. @@ -1624,11 +1632,11 @@ End Sub Creates a continuation that receives caller-supplied state information and executes asynchronously when the target completes and returns a value. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The argument is . @@ -1683,19 +1691,20 @@ End Sub Creates a continuation that executes asynchronously when the target completes and returns a value. The continuation receives a cancellation token. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> - The has been disposed. - - -or- - + The has been disposed. + + -or- + The that created the token has already been disposed. The argument is null. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1747,11 +1756,11 @@ End Sub Creates a continuation that executes according to the specified continuation options and returns a value. A new continuation . - will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - + will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + ]]> The has been disposed. @@ -1808,18 +1817,18 @@ End Sub Creates a continuation that executes asynchronously when the target completes and returns a value. The continuation uses a specified scheduler. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The has been disposed. - The argument is null. - - -or- - + The argument is null. + + -or- + The argument is null. @@ -1875,15 +1884,16 @@ End Sub Creates a continuation that executes asynchronously when the target completes and returns a value. The continuation receives caller-supplied state information and a cancellation token. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The argument is . The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1938,11 +1948,11 @@ End Sub Creates a continuation that executes based on the specified task continuation options when the target completes. The continuation receives caller-supplied state information. A new continuation . - will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - + will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + ]]> The argument is . @@ -2001,11 +2011,11 @@ End Sub Creates a continuation that executes asynchronously when the target completes. The continuation receives caller-supplied state information and uses a specified scheduler. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The argument is . @@ -2064,32 +2074,33 @@ End Sub Creates a continuation that executes according to the specified continuation options and returns a value. The continuation is passed a cancellation token and uses a specified scheduler. A new continuation . - will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - - - -## Examples - The following example shows how to use the ContinueWith method with continuation options: - + will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + + + +## Examples + The following example shows how to use the ContinueWith method with continuation options: + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/continuationoptions.cs" id="Snippet04"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/continuationoptions.vb" id="Snippet04"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/continuationoptions.vb" id="Snippet04"::: + ]]> - The has been disposed. - - -or- - + The has been disposed. + + -or- + The that created the token has already been disposed. - The argument is null. - - -or- - + The argument is null. + + -or- + The argument is null. The argument specifies an invalid value for . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2148,16 +2159,17 @@ End Sub Creates a continuation that executes based on the specified task continuation options when the target completes and returns a value. The continuation receives caller-supplied state information and a cancellation token and uses the specified scheduler. A new continuation . - will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - + will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + ]]> The argument is . The argument specifies an invalid value for . The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2240,13 +2252,13 @@ End Sub Returns the ID of the currently executing . An integer that was assigned by the system to the currently-executing task. - is a `static` (`Shared` in Visual Basic) property that is used to get the identifier of the currently executing task from the code that the task is executing. It differs from the property, which returns the identifier of a particular instance. If you attempt to retrieve the value from outside the code that a task is executing, the property returns `null`. - - Note that although collisions are very rare, task identifiers are not guaranteed to be unique. - + is a `static` (`Shared` in Visual Basic) property that is used to get the identifier of the currently executing task from the code that the task is executing. It differs from the property, which returns the identifier of a particular instance. If you attempt to retrieve the value from outside the code that a task is executing, the property returns `null`. + + Note that although collisions are very rare, task identifiers are not guaranteed to be unique. + ]]> @@ -2305,36 +2317,36 @@ End Sub Creates a task that completes after a specified number of milliseconds. A task that represents the time delay. - method is typically used to delay the operation of all or part of a task for a specified time interval. Most commonly, the time delay is introduced: - -- At the beginning of the task, as the following example shows. - + method is typically used to delay the operation of all or part of a task for a specified time interval. Most commonly, the time delay is introduced: + +- At the beginning of the task, as the following example shows. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay5.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay5.vb" id="Snippet5"::: - -- Sometime while the task is executing. In this case, the call to the method executes as a child task within a task, as the following example shows. Note that since the task that calls the method executes asynchronously, the parent task must wait for it to complete by using the `await` keyword. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay5.vb" id="Snippet5"::: + +- Sometime while the task is executing. In this case, the call to the method executes as a child task within a task, as the following example shows. Note that since the task that calls the method executes asynchronously, the parent task must wait for it to complete by using the `await` keyword. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay5.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay5.vb" id="Snippet7"::: - - After the specified time delay, the task is completed in the state. - - This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the `millisecondsDelay` argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems. + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay5.vb" id="Snippet7"::: + + After the specified time delay, the task is completed in the state. + + This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the `millisecondsDelay` argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems. > [!NOTE] > The system clock that is used is the same clock used by [GetTickCount](/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount), which is not affected by changes made with [timeBeginPeriod](/windows/win32/api/timeapi/nf-timeapi-timebeginperiod) and [timeEndPeriod](/windows/win32/api/timeapi/nf-timeapi-timeendperiod). - - - -## Examples - The following example shows a simple use of the method. - + + + +## Examples + The following example shows a simple use of the method. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay1.vb" id="Snippet1"::: + ]]> The argument is less than -1. @@ -2383,33 +2395,33 @@ End Sub Creates a task that completes after a specified time interval. A task that represents the time delay. - state. - - For usage scenarios and additional examples, see the documentation for the overload. - - This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the `delay` argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems. + state. + + For usage scenarios and additional examples, see the documentation for the overload. + + This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the `delay` argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems. > [!NOTE] > The system clock that is used is the same clock used by [GetTickCount](/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount), which is not affected by changes made with [timeBeginPeriod](/windows/win32/api/timeapi/nf-timeapi-timebeginperiod) and [timeEndPeriod](/windows/win32/api/timeapi/nf-timeapi-timeendperiod). - - - -## Examples - The following example shows a simple use of the method. - + + + +## Examples + The following example shows a simple use of the method. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay2.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay2.vb" id="Snippet2"::: + ]]> - represents a negative time interval other than . - - -or- - + represents a negative time interval other than . + + -or- + The argument's property is greater than 4294967294 on .NET 6 and later versions, or Int32.MaxValue on all previous versions. @@ -2458,31 +2470,32 @@ End Sub Creates a cancellable task that completes after a specified number of milliseconds. A task that represents the time delay. - exception results, and the task is completed in the state. Otherwise, the task is completed in the state once the specified time delay has elapsed. - - For usage scenarios and additional examples, see the documentation for the overload. - - This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the `millisecondsDelay` argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems. + exception results, and the task is completed in the state. Otherwise, the task is completed in the state once the specified time delay has elapsed. + + For usage scenarios and additional examples, see the documentation for the overload. + + This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the `millisecondsDelay` argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems. > [!NOTE] > The system clock that is used is the same clock used by [GetTickCount](/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount), which is not affected by changes made with [timeBeginPeriod](/windows/win32/api/timeapi/nf-timeapi-timebeginperiod) and [timeEndPeriod](/windows/win32/api/timeapi/nf-timeapi-timeendperiod). - - - -## Examples - The following example launches a task that includes a call to the method with a one second delay. Before the delay interval elapses, the token is cancelled. The output from the example shows that, as a result, a is thrown, and the tasks' property is set to . - + + + +## Examples + The following example launches a task that includes a call to the method with a one second delay. Before the delay interval elapses, the token is cancelled. The output from the example shows that, as a result, a is thrown, and the tasks' property is set to . + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay3.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay3.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay3.vb" id="Snippet3"::: + ]]> The argument is less than -1. The task has been canceled. The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2530,42 +2543,43 @@ End Sub Creates a cancellable task that completes after a specified time interval. A task that represents the time delay. - exception results, and the task is completed in the state. Otherwise, the task is completed in the state once the specified time delay has elapsed. - - For usage scenarios and additional examples, see the documentation for the overload. - - This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the `delay` argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems. + exception results, and the task is completed in the state. Otherwise, the task is completed in the state once the specified time delay has elapsed. + + For usage scenarios and additional examples, see the documentation for the overload. + + This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the `delay` argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems. > [!NOTE] > The system clock that is used is the same clock used by [GetTickCount](/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount), which is not affected by changes made with [timeBeginPeriod](/windows/win32/api/timeapi/nf-timeapi-timebeginperiod) and [timeEndPeriod](/windows/win32/api/timeapi/nf-timeapi-timeendperiod). - - - -## Examples - The following example launches a task that includes a call to the method with a 1.5 second delay. Before the delay interval elapses, the token is cancelled. The output from the example shows that, as a result, a is thrown, and the tasks' property is set to . - + + + +## Examples + The following example launches a task that includes a call to the method with a 1.5 second delay. Before the delay interval elapses, the token is cancelled. The output from the example shows that, as a result, a is thrown, and the tasks' property is set to . + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay4.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay4.vb" id="Snippet4"::: - - Note that this example includes a potential race condition: it depends on the task asynchronously executing the delay when the token is cancelled. Although the 1.5 second delay from the call to the method makes that assumption likely, it is nevertheless possible that the call to the method could return before the token is cancelled. In that case, the example produces the following output: - -``` -Task t Status: RanToCompletion, Result: 42 -``` - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay4.vb" id="Snippet4"::: + + Note that this example includes a potential race condition: it depends on the task asynchronously executing the delay when the token is cancelled. Although the 1.5 second delay from the call to the method makes that assumption likely, it is nevertheless possible that the call to the method could return before the token is cancelled. In that case, the example produces the following output: + +``` +Task t Status: RanToCompletion, Result: 42 +``` + ]]> - represents a negative time interval other than . - - -or- - + represents a negative time interval other than . + + -or- + The argument's property is greater than 4294967294 on .NET 6 and later versions, or Int32.MaxValue on all previous versions. The task has been canceled. The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2618,11 +2632,11 @@ Task t Status: RanToCompletion, Result: 42 Releases all resources used by the current instance of the class. - class implements the interface because internally it uses resources that also implement . However, particularly if your app targets the .NET Framework 4.5 or later, there is no need to call unless performance or scalability testing indicates that, based on your usage patterns, your app's performance would be improved by disposing of tasks. For more information, see [Do I need to dispose of Tasks?](https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/) in the Parallel Programming with .NET blog. - + class implements the interface because internally it uses resources that also implement . However, particularly if your app targets the .NET Framework 4.5 or later, there is no need to call unless performance or scalability testing indicates that, based on your usage patterns, your app's performance would be improved by disposing of tasks. For more information, see [Do I need to dispose of Tasks?](https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/) in the Parallel Programming with .NET blog. + ]]> The task is not in one of the final states: , , or . @@ -2668,11 +2682,11 @@ Task t Status: RanToCompletion, Result: 42 A Boolean value that indicates whether this method is being called due to a call to . Disposes the , releasing all of its unmanaged resources. - class implements the interface because internally it uses resources that also implement . However, particularly if your app targets the .NET Framework 4.5 or later, there is no need to call unless performance or scalability testing indicates that, based on your usage patterns, your app's performance would be improved by disposing of tasks. For more information, see [Do I need to dispose of Tasks?](https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/) in the Parallel Programming with .NET blog. - + class implements the interface because internally it uses resources that also implement . However, particularly if your app targets the .NET Framework 4.5 or later, there is no need to call unless performance or scalability testing indicates that, based on your usage patterns, your app's performance would be improved by disposing of tasks. For more information, see [Do I need to dispose of Tasks?](https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/) in the Parallel Programming with .NET blog. + ]]> The task is not in one of the final states: , , or . @@ -2719,11 +2733,11 @@ Task t Status: RanToCompletion, Result: 42 Gets the that caused the to end prematurely. If the completed successfully or has not yet thrown any exceptions, this will return . The that caused the to end prematurely. - in calls to or in accesses to the property. On .NET Framework 4.0, any exceptions not observed by the time the task instance is garbage collected will be propagated on the finalizer thread, which crashes the process. On .NET Framework 4.5 and later the default behavior changed so unobserved exceptions are not rethrown from the Finalizer. .NET Core does not rethrow the exception on the Finalizer. For more information and an example, see [Exception Handling (Task Parallel Library)](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). - + in calls to or in accesses to the property. On .NET Framework 4.0, any exceptions not observed by the time the task instance is garbage collected will be propagated on the finalizer thread, which crashes the process. On .NET Framework 4.5 and later the default behavior changed so unobserved exceptions are not rethrown from the Finalizer. .NET Core does not rethrow the exception on the Finalizer. For more information and an example, see [Exception Handling (Task Parallel Library)](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). + ]]> @@ -2767,28 +2781,28 @@ Task t Status: RanToCompletion, Result: 42 Provides access to factory methods for creating and configuring and instances. A factory object that can create a variety of and objects. - class that is identical to the one created by calling the parameterless constructor. It has the following property values: - -|Property|Value| -|--------------|-----------| -||| -||| -||| -||`null`, or | - - The most common use of this property is to create and start a new task in a single call to the method. - + class that is identical to the one created by calling the parameterless constructor. It has the following property values: + +|Property|Value| +|--------------|-----------| +||| +||| +||| +||`null`, or | + + The most common use of this property is to create and start a new task in a single call to the method. + > [!NOTE] -> Starting with the .NET Framework 4.5, the method provides the easiest way to create a object with default configuration values. - - The following example uses the static property to make two calls to the method. The first populates an array with the names of files in the user's MyDocuments directory, while the second populates an array with the names of subdirectories of the user's MyDocuments directory. It then calls the method, which displays information about the number of files and directories in the two arrays after the first two tasks have completed execution. - +> Starting with the .NET Framework 4.5, the method provides the easiest way to create a object with default configuration values. + + The following example uses the static property to make two calls to the method. The first populates an array with the names of files in the user's MyDocuments directory, while the second populates an array with the names of subdirectories of the user's MyDocuments directory. It then calls the method, which displays information about the number of files and directories in the two arrays after the first two tasks have completed execution. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Factory/factory1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.factory/vb/factory1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.factory/vb/factory1.vb" id="Snippet1"::: + ]]> @@ -2837,6 +2851,7 @@ Task t Status: RanToCompletion, Result: 42 The canceled task. To be added. Cancellation has not been requested for ; its property is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2886,6 +2901,7 @@ Task t Status: RanToCompletion, Result: 42 The canceled task. To be added. Cancellation has not been requested for ; its property is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2930,11 +2946,11 @@ Task t Status: RanToCompletion, Result: 42 Creates a that has completed with a specified exception. The faulted task. - object whose property is and whose property contains `exception`. The method is commonly used when you immediately know that the work that a task performs will throw an exception before executing a longer code path. For an example, see the overload. - + object whose property is and whose property contains `exception`. The method is commonly used when you immediately know that the work that a task performs will throw an exception before executing a longer code path. For an example, see the overload. + ]]> @@ -2985,19 +3001,19 @@ Task t Status: RanToCompletion, Result: 42 Creates a that's completed with a specified exception. The faulted task. - object whose property is and whose property contains `exception`. The method is commonly used when you immediately know that the work that a task performs will throw an exception before executing a longer code path. The example provides an illustration. - - - -## Examples - The following example is a command-line utility that calculates the number of bytes in the files in each directory whose name is passed as a command-line argument. Rather than executing a longer code path that instantiates a object and retrieves the value of its property for each file in the directory, the example simply calls the method to create a faulted task if a particular subdirectory does not exist. - + object whose property is and whose property contains `exception`. The method is commonly used when you immediately know that the work that a task performs will throw an exception before executing a longer code path. The example provides an illustration. + + + +## Examples + The following example is a command-line utility that calculates the number of bytes in the files in each directory whose name is passed as a command-line argument. Rather than executing a longer code path that instantiates a object and retrieves the value of its property for each file in the directory, the example simply calls the method to create a faulted task if a particular subdirectory does not exist. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.fromresult/vb/fromresult1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.fromresult/vb/fromresult1.vb" id="Snippet1"::: + ]]> @@ -3049,22 +3065,22 @@ Task t Status: RanToCompletion, Result: 42 Creates a that's completed successfully with the specified result. The successfully completed task. - object whose property is `result` and whose property is . The method is commonly used when the return value of a task is immediately known without executing a longer code path. The example provides an illustration. To create a `Task` object that does not return a value, retrieve the `Task` object from the property. -Starting in .NET 6, for some `TResult` types and some result values, this method may return a cached singleton object rather than allocating a new object. - -## Examples - The following example is a command-line utility that calculates the number of bytes in the files in each directory whose name is passed as a command-line argument. Rather than executing a longer code path that instantiates a object and retrieves the value of its property for each file in the directory, the example simply calls the method to create a task whose property is zero (0) if a directory has no files. - +Starting in .NET 6, for some `TResult` types and some result values, this method may return a cached singleton object rather than allocating a new object. + +## Examples + The following example is a command-line utility that calculates the number of bytes in the files in each directory whose name is passed as a command-line argument. Rather than executing a longer code path that instantiates a object and retrieves the value of its property for each file in the directory, the example simply calls the method to create a task whose property is zero (0) if a directory has no files. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.fromresult/vb/fromresult1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.fromresult/vb/fromresult1.vb" id="Snippet1"::: + ]]> @@ -3165,13 +3181,13 @@ This method is intended for compiler use rather than use directly in code. Gets an ID for this instance. The identifier that is assigned by the system to this instance. - property. - + property. + ]]> @@ -3217,20 +3233,20 @@ This method is intended for compiler use rather than use directly in code. if the task has completed due to being canceled; otherwise . - will complete in the state under any of the following conditions: - -- Its was marked for cancellation before the task started executing, - -- The task acknowledged the cancellation request on its already signaled by throwing an that bears the same . - -- The task acknowledged the cancellation request on its already signaled by calling the method on the . - + will complete in the state under any of the following conditions: + +- Its was marked for cancellation before the task started executing, + +- The task acknowledged the cancellation request on its already signaled by throwing an that bears the same . + +- The task acknowledged the cancellation request on its already signaled by calling the method on the . + > [!IMPORTANT] -> Retrieving the value of the property does not block the calling thread until the task has completed. - +> Retrieving the value of the property does not block the calling thread until the task has completed. + ]]> @@ -3284,13 +3300,13 @@ This method is intended for compiler use rather than use directly in code. if the task has completed (that is, the task is in one of the three final states: , , or ); otherwise, . - [!IMPORTANT] -> Retrieving the value of the property does not block the calling thread until the task has completed. - +> Retrieving the value of the property does not block the calling thread until the task has completed. + ]]> @@ -3372,14 +3388,14 @@ This method is intended for compiler use rather than use directly in code. if the task has thrown an unhandled exception; otherwise . - is `true`, the task's is equal to , and its property will be non-null. - + is `true`, the task's is equal to , and its property will be non-null. + > [!IMPORTANT] -> Retrieving the value of the property does not block the calling thread until the task has completed. - +> Retrieving the value of the property does not block the calling thread until the task has completed. + ]]> @@ -3393,11 +3409,11 @@ This method is intended for compiler use rather than use directly in code. Queues the specified work to run on the ThreadPool and returns a task or handle for that work. - method provides a set of overloads that make it easy to start a task by using default values. It is a lightweight alternative to the overloads. - + method provides a set of overloads that make it easy to start a task by using default values. It is a lightweight alternative to the overloads. + ]]> @@ -3445,41 +3461,41 @@ This method is intended for compiler use rather than use directly in code. Queues the specified work to run on the thread pool and returns a object that represents that work. A task that represents the work queued to execute in the ThreadPool. - method allows you to create and execute a task in a single method call and is a simpler alternative to the method. It creates a task with the following default values: - -- Its cancellation token is . - -- Its property value is . - -- It uses the default task scheduler. - - For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). - - - -## Examples - The following example defines a `ShowThreadInfo` method that displays the of the current thread. It is called directly from the application thread, and is called from the delegate passed to the method. - + method allows you to create and execute a task in a single method call and is a simpler alternative to the method. It creates a task with the following default values: + +- Its cancellation token is . + +- Its property value is . + +- It uses the default task scheduler. + + For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). + + + +## Examples + The following example defines a `ShowThreadInfo` method that displays the of the current thread. It is called directly from the application thread, and is called from the delegate passed to the method. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/Run11.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run11.vb" id="Snippet11"::: - - The following example is similar to the previous one, except that it uses a lambda expression to define the code that the task is to execute. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run11.vb" id="Snippet11"::: + + The following example is similar to the previous one, except that it uses a lambda expression to define the code that the task is to execute. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run6.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run6.vb" id="Snippet3"::: - - The examples show that the asynchronous task executes on a different thread than the main application thread. - - The call to the method ensures that the task completes and displays its output before the application ends. Otherwise, it is possible that the `Main` method will complete before the task finishes. - - The following example illustrates the method. It defines an array of directory names and starts a separate task to retrieve the file names in each directory. All tasks write the file names to a single object. The example then calls the method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the object. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run6.vb" id="Snippet3"::: + + The examples show that the asynchronous task executes on a different thread than the main application thread. + + The call to the method ensures that the task completes and displays its output before the application ends. Otherwise, it is possible that the `Main` method will complete before the task finishes. + + The following example illustrates the method. It defines an array of directory names and starts a separate task to retrieve the file names in each directory. All tasks write the file names to a single object. The example then calls the method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the object. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run2.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run2.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run2.vb" id="Snippet1"::: + ]]> The parameter was . @@ -3530,11 +3546,11 @@ This method is intended for compiler use rather than use directly in code. Queues the specified work to run on the thread pool and returns a proxy for the task returned by . A task that represents a proxy for the task returned by . - The parameter was . @@ -3586,33 +3602,34 @@ This method is intended for compiler use rather than use directly in code. Queues the specified work to run on the thread pool and returns a object that represents that work. A cancellation token allows the work to be cancelled if it has not yet started. A task that represents the work queued to execute in the thread pool. - state and throws a exception. - - The method is a simpler alternative to the method. It creates a task with the following default values: - -- Its property value is . - -- It uses the default task scheduler. - - For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). - - - -## Examples - The following example calls the method to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the method to add information about each file to a object. Each detached nested task invoked by the loop checks the state of the cancellation token and, if cancellation is requested, calls the method. The method throws an exception that is handled in a `catch` block when the calling thread calls the method. - + state and throws a exception. + + The method is a simpler alternative to the method. It creates a task with the following default values: + +- Its property value is . + +- It uses the default task scheduler. + + For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). + + + +## Examples + The following example calls the method to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the method to add information about each file to a object. Each detached nested task invoked by the loop checks the state of the cancellation token and, if cancellation is requested, calls the method. The method throws an exception that is handled in a `catch` block when the calling thread calls the method. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run41.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run4.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run4.vb" id="Snippet4"::: + ]]> The parameter was . The task has been canceled. The associated with was disposed. Exception Handling (Task Parallel Library) + The cancellation token was canceled. This exception is stored into the returned task. @@ -3661,11 +3678,11 @@ This method is intended for compiler use rather than use directly in code. Queues the specified work to run on the thread pool and returns a proxy for the task returned by . A cancellation token allows the work to be cancelled if it has not yet started. A task that represents a proxy for the task returned by . - The parameter was . @@ -3673,6 +3690,7 @@ This method is intended for compiler use rather than use directly in code. The associated with was disposed. Task Cancellation Exception Handling (Task Parallel Library) + The cancellation token was canceled. This exception is stored into the returned task. @@ -3723,11 +3741,11 @@ This method is intended for compiler use rather than use directly in code. Queues the specified work to run on the thread pool and returns a proxy for the returned by . A cancellation token allows the work to be cancelled if it has not yet started. A that represents a proxy for the returned by . - The parameter was . @@ -3781,29 +3799,29 @@ This method is intended for compiler use rather than use directly in code. Queues the specified work to run on the thread pool and returns a object that represents that work. A cancellation token allows the work to be cancelled if it has not yet started. A task object that represents the work queued to execute in the thread pool. - method is a simpler alternative to the method. It creates a task with the following default values: - -- Its cancellation token is . - -- Its property value is . - -- It uses the default task scheduler. - - For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). - - - -## Examples - The following example counts the approximate number of words in text files that represent published books. Each task is responsible for opening a file, reading its entire contents asynchronously, and calculating the word count by using a regular expression. The method is called to ensure that all tasks have completed before displaying the word count of each book to the console. - + method is a simpler alternative to the method. It creates a task with the following default values: + +- Its cancellation token is . + +- Its property value is . + +- It uses the default task scheduler. + + For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). + + + +## Examples + The following example counts the approximate number of words in text files that represent published books. Each task is responsible for opening a file, reading its entire contents asynchronously, and calculating the word count by using a regular expression. The method is called to ensure that all tasks have completed before displaying the word count of each book to the console. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run31.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run3.vb" id="Snippet2"::: - - The regular expression `\p{P}*\s+` matches zero, one, or more punctuation characters followed by one or more white-space characters. It assumes that the total number of matches equals the approximate word count. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run3.vb" id="Snippet2"::: + + The regular expression `\p{P}*\s+` matches zero, one, or more punctuation characters followed by one or more white-space characters. It assumes that the total number of matches equals the approximate word count. + ]]> The parameter is . @@ -3860,11 +3878,11 @@ This method is intended for compiler use rather than use directly in code. Queues the specified work to run on the thread pool and returns a proxy for the returned by . A that represents a proxy for the returned by . - The parameter was . @@ -3872,6 +3890,7 @@ This method is intended for compiler use rather than use directly in code. The associated with was disposed. Task Cancellation Exception Handling (Task Parallel Library) + The cancellation token was canceled. This exception is stored into the returned task. @@ -3923,36 +3942,36 @@ This method is intended for compiler use rather than use directly in code. Queues the specified work to run on the thread pool and returns a object that represents that work. A that represents the work queued to execute in the thread pool. - state and throws a exception. - - The method is a simpler alternative to the method. It creates a task with the following default values: - -- Its property value is . - -- It uses the default task scheduler. - - For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). - - - -## Examples - The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. The example shows possible output. - + state and throws a exception. + + The method is a simpler alternative to the method. It creates a task with the following default values: + +- Its property value is . + +- It uses the default task scheduler. + + For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). + + + +## Examples + The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. The example shows possible output. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/Run7.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run7.vb" id="Snippet7"::: - - Instead of using the property to examine exceptions, the example iterates all tasks to determine which have completed successfully and which have been cancelled. For those that have completed, it displays the value returned by the task. - - Because cancellation is cooperative, each task can decide how to respond to cancellation. The following example is like the first, except that, once the token is cancelled, tasks return the number of iterations they've completed rather than throw an exception. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run7.vb" id="Snippet7"::: + + Instead of using the property to examine exceptions, the example iterates all tasks to determine which have completed successfully and which have been cancelled. For those that have completed, it displays the value returned by the task. + + Because cancellation is cooperative, each task can decide how to respond to cancellation. The following example is like the first, except that, once the token is cancelled, tasks return the number of iterations they've completed rather than throw an exception. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/Run28.cs" id="Snippet28"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run28.vb" id="Snippet28"::: - - The example still must handle the exception, since any tasks that have not started when cancellation is requested still throw an exception. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run28.vb" id="Snippet28"::: + + The example still must handle the exception, since any tasks that have not started when cancellation is requested still throw an exception. + ]]> The parameter is . @@ -3960,6 +3979,7 @@ This method is intended for compiler use rather than use directly in code. The associated with was disposed. Task Cancellation Exception Handling (Task Parallel Library) + The cancellation token was canceled. This exception is stored into the returned task. @@ -4011,21 +4031,21 @@ This method is intended for compiler use rather than use directly in code. Runs the synchronously on the current . - method are associated with the current and are run on the calling thread. If the target scheduler does not support running this task on the calling thread, the task will be scheduled for execution on the scheduler, and the calling thread will block until the task has completed execution. Even though the task runs synchronously, the calling thread should still call to handle any exceptions that the task might throw. For more information on exception handling, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). - - Tasks executed by calling the method are instantiated by calling a or class constructor. The task to be run synchronously must be in the state. A task may be started and run only once. Any attempts to schedule a task a second time results in an exception. - - - -## Examples - The following example compares a task executed by calling the method with one executed asynchronously. In both cases, the tasks execute identical lambda expressions that display the task ID and the ID of the thread on which the task is running. The task calculates the sum of the integers between 1 and 1,000,000. As the output from the example shows, the task executed by calling the method runs on the application thread, while the asynchronous task does not. - + method are associated with the current and are run on the calling thread. If the target scheduler does not support running this task on the calling thread, the task will be scheduled for execution on the scheduler, and the calling thread will block until the task has completed execution. Even though the task runs synchronously, the calling thread should still call to handle any exceptions that the task might throw. For more information on exception handling, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). + + Tasks executed by calling the method are instantiated by calling a or class constructor. The task to be run synchronously must be in the state. A task may be started and run only once. Any attempts to schedule a task a second time results in an exception. + + + +## Examples + The following example compares a task executed by calling the method with one executed asynchronously. In both cases, the tasks execute identical lambda expressions that display the task ID and the ID of the thread on which the task is running. The task calculates the sum of the integers between 1 and 1,000,000. As the output from the example shows, the task executed by calling the method runs on the application thread, while the asynchronous task does not. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/RunSynchronously/runsynchronously1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.runsynchronously/vb/runsynchronously1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.runsynchronously/vb/runsynchronously1.vb" id="Snippet1"::: + ]]> The instance has been disposed. @@ -4075,13 +4095,13 @@ This method is intended for compiler use rather than use directly in code. The scheduler on which to attempt to run this task inline. Runs the synchronously on the provided. - method are instantiated by calling a or class constructor. The task to be run synchronously must be in the state. A task may be started and run only once. Any attempts to schedule a task a second time results in an exception. - - If the target scheduler does not support running this task on the current thread, the task will be scheduled for execution on the scheduler, and the current thread will block until the task has completed execution. Because of this, the calling thread does not need to call a method such as to ensure that the task has completed execution. For more information on exception handling for task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). - + method are instantiated by calling a or class constructor. The task to be run synchronously must be in the state. A task may be started and run only once. Any attempts to schedule a task a second time results in an exception. + + If the target scheduler does not support running this task on the current thread, the task will be scheduled for execution on the scheduler, and the current thread will block until the task has completed execution. Because of this, the calling thread does not need to call a method such as to ensure that the task has completed execution. For more information on exception handling for task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). + ]]> The instance has been disposed. @@ -4140,23 +4160,23 @@ This method is intended for compiler use rather than use directly in code. Starts the , scheduling it for execution to the current . - is used to execute a task that has been created by calling one of the constructors. Typically, you do this when you need to separate the task's creation from its execution, such as when you conditionally execute tasks that you've created. For the more common case in which you don't need to separate task instantiation from execution, we recommend that you call an overload of the or method. - - For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). - - - -## Examples - The following example calls the constructor to instantiate a new object that displays its task ID and managed thread ID and then executes a loop. It then calls the method to execute the task. Since this is a console app, the call to the method is necessary to prevent the app from terminating before the task finishes execution. - + is used to execute a task that has been created by calling one of the constructors. Typically, you do this when you need to separate the task's creation from its execution, such as when you conditionally execute tasks that you've created. For the more common case in which you don't need to separate task instantiation from execution, we recommend that you call an overload of the or method. + + For information on handling exceptions thrown by task operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library). + + + +## Examples + The following example calls the constructor to instantiate a new object that displays its task ID and managed thread ID and then executes a loop. It then calls the method to execute the task. Since this is a console app, the call to the method is necessary to prevent the app from terminating before the task finishes execution. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Start/Start1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.start/vb/Start1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.start/vb/Start1.vb" id="Snippet1"::: + ]]> The instance has been disposed. @@ -4206,13 +4226,13 @@ This method is intended for compiler use rather than use directly in code. The with which to associate and execute this task. Starts the , scheduling it for execution to the specified . - The argument is . @@ -4261,21 +4281,21 @@ This method is intended for compiler use rather than use directly in code. Gets the of this task. The current of this task instance. - property does not block the calling thread until the task has completed. - - For more information and an example, see [Chaining Tasks by Using Continuation Tasks](/dotnet/standard/parallel-programming/chaining-tasks-by-using-continuation-tasks) and [How to: Cancel a Task and Its Children](/dotnet/standard/parallel-programming/how-to-cancel-a-task-and-its-children). - - - -## Examples - The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. The example then examines the property of each task to indicate whether it completed successfully or was cancelled. For those that completed, it displays the value returned by the task. - + property does not block the calling thread until the task has completed. + + For more information and an example, see [Chaining Tasks by Using Continuation Tasks](/dotnet/standard/parallel-programming/chaining-tasks-by-using-continuation-tasks) and [How to: Cancel a Task and Its Children](/dotnet/standard/parallel-programming/how-to-cancel-a-task-and-its-children). + + + +## Examples + The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. The example then examines the property of each task to indicate whether it completed successfully or was cancelled. For those that completed, it displays the value returned by the task. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/Run7.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run7.vb" id="Snippet7"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run7.vb" id="Snippet7"::: + ]]> @@ -4322,11 +4342,11 @@ This method is intended for compiler use rather than use directly in code. Gets a that can be used to wait for the task to complete. A that can be used to wait for the task to complete. - is preferable to using for similar functionality. For more information, see the "Waiting on Tasks" section in [Task-based Asynchronous Programming](/dotnet/standard/parallel-programming/task-based-asynchronous-programming) and [Using TPL with Other Asynchronous Patterns](/dotnet/standard/parallel-programming/using-tpl-with-other-asynchronous-patterns). - + is preferable to using for similar functionality. For more information, see the "Waiting on Tasks" section in [Task-based Asynchronous Programming](/dotnet/standard/parallel-programming/task-based-asynchronous-programming) and [Using TPL with Other Asynchronous Patterns](/dotnet/standard/parallel-programming/using-tpl-with-other-asynchronous-patterns). + ]]> The has been disposed. @@ -4434,24 +4454,24 @@ This member is an explicit interface member implementation. It can be used only Waits for the to complete execution. - is a synchronization method that causes the calling thread to wait until the current task has completed. If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread. If it is unable to do that, or if the current task has already started execution, it blocks the calling thread until the task completes. For more information, see [Task.Wait and "Inlining"](https://devblogs.microsoft.com/pfxteam/task-wait-and-inlining/) in the Parallel Programming with .NET blog. - -## Examples - The following example starts a task that generates one million random integers between 0 and 100 and computes their mean. The example uses the method to ensure that the task completes before the application terminates. Otherwise, because this is a console application, the example would terminate before the task can compute and display the mean. - + is a synchronization method that causes the calling thread to wait until the current task has completed. If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread. If it is unable to do that, or if the current task has already started execution, it blocks the calling thread until the task completes. For more information, see [Task.Wait and "Inlining"](https://devblogs.microsoft.com/pfxteam/task-wait-and-inlining/) in the Parallel Programming with .NET blog. + +## Examples + The following example starts a task that generates one million random integers between 0 and 100 and computes their mean. The example uses the method to ensure that the task completes before the application terminates. Otherwise, because this is a console application, the example would terminate before the task can compute and display the mean. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/wait1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/wait1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/wait1.vb" id="Snippet1"::: + ]]> The has been disposed. - The task was canceled. The collection contains a object. - - -or- - + The task was canceled. The collection contains a object. + + -or- + An exception was thrown during the execution of the task. The collection contains information about the exception or exceptions. Task.Wait and "Inlining" @@ -4500,34 +4520,34 @@ This member is an explicit interface member implementation. It can be used only if the completed execution within the allotted time; otherwise, . - is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs: - -- The task completes successfully. - -- The task itself is canceled or throws an exception. In this case, you handle an exception. The property contains details about the exception or exceptions. - -- The interval defined by `millisecondsTimeout` elapses. In this case, the current thread resumes execution and the method returns `false`. - - - -## Examples - The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. The example uses the method to wait for the application to complete within 150 milliseconds. If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. If the timeout interval has elapsed, the example displays a message before it terminates. - + is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs: + +- The task completes successfully. + +- The task itself is canceled or throws an exception. In this case, you handle an exception. The property contains details about the exception or exceptions. + +- The interval defined by `millisecondsTimeout` elapses. In this case, the current thread resumes execution and the method returns `false`. + + + +## Examples + The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. The example uses the method to wait for the application to complete within 150 milliseconds. If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. If the timeout interval has elapsed, the example displays a message before it terminates. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/Wait5.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/Wait5.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/Wait5.vb" id="Snippet5"::: + ]]> The has been disposed. is a negative number other than -1, which represents an infinite time-out. - The task was canceled. The collection contains a object. - - -or- - + The task was canceled. The collection contains a object. + + -or- + An exception was thrown during the execution of the task. The collection contains information about the exception or exceptions. @@ -4573,34 +4593,34 @@ This member is an explicit interface member implementation. It can be used only A cancellation token to observe while waiting for the task to complete. Waits for the to complete execution. The wait terminates if a cancellation token is canceled before the task completes. - method creates a cancelable wait; that is, it causes the current thread to wait until one of the following occurs: - -- The task completes. - -- The cancellation token is canceled. In this case, the call to the method throws an . - + method creates a cancelable wait; that is, it causes the current thread to wait until one of the following occurs: + +- The task completes. + +- The cancellation token is canceled. In this case, the call to the method throws an . + > [!NOTE] -> Canceling the `cancellationToken` cancellation token has no effect on the running task unless it has also been passed the cancellation token and is prepared to handle cancellation. Passing the `cancellationToken` object to this method simply allows the wait to be canceled. - - - -## Examples - The following example illustrates the simple use of a cancellation token to cancel waiting for a task's completion. A task is launched, calls the method to cancel any of the token source's cancellation tokens, and then delays for five seconds. Note that the task itself has not been passed the cancellation token and is not cancelable. The application thread calls the task's method to wait for the task to complete, but the wait is canceled once the cancellation token is cancelled and an is thrown. The exception handler reports the exception and then sleeps for six seconds. As the output from the example shows, that delay allows the task to complete in the state. - +> Canceling the `cancellationToken` cancellation token has no effect on the running task unless it has also been passed the cancellation token and is prepared to handle cancellation. Passing the `cancellationToken` object to this method simply allows the wait to be canceled. + + + +## Examples + The following example illustrates the simple use of a cancellation token to cancel waiting for a task's completion. A task is launched, calls the method to cancel any of the token source's cancellation tokens, and then delays for five seconds. Note that the task itself has not been passed the cancellation token and is not cancelable. The application thread calls the task's method to wait for the task to complete, but the wait is canceled once the cancellation token is cancelled and an is thrown. The exception handler reports the exception and then sleeps for six seconds. As the output from the example shows, that delay allows the task to complete in the state. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/wait3.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/wait3.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/wait3.vb" id="Snippet3"::: + ]]> The was canceled. The task has been disposed. - The task was canceled. The collection contains a object. - - -or- - + The task was canceled. The collection contains a object. + + -or- + An exception was thrown during the execution of the task. The collection contains information about the exception or exceptions. @@ -4648,38 +4668,38 @@ This member is an explicit interface member implementation. It can be used only if the completed execution within the allotted time; otherwise, . - is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs: - -- The task completes successfully. - -- The task itself is canceled or throws an exception. In this case, you handle an exception. The property contains details about the exception or exceptions. - -- The interval defined by `timeout` elapses. In this case, the current thread resumes execution and the method returns `false`. - - - -## Examples - The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. The example uses the method to wait for the application to complete within 150 milliseconds. If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. If the timeout interval has elapsed, the example displays a message before it terminates. - + is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs: + +- The task completes successfully. + +- The task itself is canceled or throws an exception. In this case, you handle an exception. The property contains details about the exception or exceptions. + +- The interval defined by `timeout` elapses. In this case, the current thread resumes execution and the method returns `false`. + + + +## Examples + The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. The example uses the method to wait for the application to complete within 150 milliseconds. If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. If the timeout interval has elapsed, the example displays a message before it terminates. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/Wait6.cs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/Wait6.vb" id="Snippet6"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/Wait6.vb" id="Snippet6"::: + ]]> The has been disposed. - is a negative number other than -1 milliseconds, which represents an infinite time-out. - - -or- - + is a negative number other than -1 milliseconds, which represents an infinite time-out. + + -or- + is greater than Int32.MaxValue. - The task was canceled. The collection contains a object. - - -or- - + The task was canceled. The collection contains a object. + + -or- + An exception was thrown during the execution of the task. The collection contains information about the exception or exceptions. @@ -4729,42 +4749,42 @@ This member is an explicit interface member implementation. It can be used only if the completed execution within the allotted time; otherwise, . - is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs: - -- The task completes successfully. - -- The task itself is canceled or throws an exception. In this case, you handle an exception. The property contains details about the exception or exceptions. - -- The `cancellationToken` cancellation token is canceled. In this case, the call to the method throws an . - -- The interval defined by `millisecondsTimeout` elapses. In this case, the current thread resumes execution and the method returns `false`. - + is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs: + +- The task completes successfully. + +- The task itself is canceled or throws an exception. In this case, you handle an exception. The property contains details about the exception or exceptions. + +- The `cancellationToken` cancellation token is canceled. In this case, the call to the method throws an . + +- The interval defined by `millisecondsTimeout` elapses. In this case, the current thread resumes execution and the method returns `false`. + > [!NOTE] -> Canceling the `cancellationToken` cancellation token has no effect on the running task unless it has also been passed the cancellation token and is prepared to handle cancellation. Passing the `cancellationToken` object to this method simply allows the wait to be canceled based on some condition. - - - -## Examples - The following example calls the method to provide both a timeout value and a cancellation token that can end the wait for a task's completion. A new thread is started and executes the `CancelToken` method, which pauses and then calls the method to cancel the cancellation tokens. A task is then launched and delays for 5 seconds. The method is then called to wait for the task's completion and is provided both a brief timeout value and a cancellation token. - +> Canceling the `cancellationToken` cancellation token has no effect on the running task unless it has also been passed the cancellation token and is prepared to handle cancellation. Passing the `cancellationToken` object to this method simply allows the wait to be canceled based on some condition. + + + +## Examples + The following example calls the method to provide both a timeout value and a cancellation token that can end the wait for a task's completion. A new thread is started and executes the `CancelToken` method, which pauses and then calls the method to cancel the cancellation tokens. A task is then launched and delays for 5 seconds. The method is then called to wait for the task's completion and is provided both a brief timeout value and a cancellation token. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/wait4.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/wait4.vb" id="Snippet4"::: - - Note that the precise output from the example depends on whether the wait was canceled because of the cancellation token or because the timeout interval elapsed. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/wait4.vb" id="Snippet4"::: + + Note that the precise output from the example depends on whether the wait was canceled because of the cancellation token or because the timeout interval elapsed. + ]]> The was canceled. The has been disposed. is a negative number other than -1, which represents an infinite time-out. - The task was canceled. The collection contains a object. - - -or- - + The task was canceled. The collection contains a object. + + -or- + An exception was thrown during the execution of the task. The collection contains information about the exception or exceptions. @@ -4884,23 +4904,23 @@ timeout is greater than An array of instances on which to wait. Waits for all of the provided objects to complete execution. - method wraps all exceptions in an object and propagates it to the calling thread. - + method wraps all exceptions in an object and propagates it to the calling thread. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/waitall.cs" id="Snippet02"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/waitall.vb" id="Snippet02"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/waitall.vb" id="Snippet02"::: + ]]> One or more of the objects in has been disposed. The argument is . The argument contains a null element. - At least one of the instances was canceled. If a task was canceled, the exception contains an exception in its collection. - - -or- - + At least one of the instances was canceled. If a task was canceled, the exception contains an exception in its collection. + + -or- + An exception was thrown during the execution of at least one of the instances. @@ -4958,10 +4978,10 @@ timeout is greater than To be added. One or more of the objects in has been disposed. The argument is . - At least one of the instances was canceled. If a task was canceled, the contains an in its collection. - - -or- - + At least one of the instances was canceled. If a task was canceled, the contains an in its collection. + + -or- + An exception was thrown during the execution of at least one of the instances. is a negative number other than -1, which represents an infinite time-out. @@ -5018,19 +5038,19 @@ timeout is greater than A to observe while waiting for the tasks to complete. Waits for all of the provided objects to complete execution unless the wait is cancelled. - as noted above. - + as noted above. + ]]> The was canceled. The argument is . - At least one of the instances was canceled. If a task was canceled, the contains an in its collection. - - -or- - + At least one of the instances was canceled. If a task was canceled, the contains an in its collection. + + -or- + An exception was thrown during the execution of at least one of the instances. The argument contains a null element. One or more of the objects in has been disposed. @@ -5090,16 +5110,16 @@ timeout is greater than To be added. One or more of the objects in has been disposed. The argument is . - At least one of the instances was canceled. If a task was canceled, the contains an in its collection. - - -or- - + At least one of the instances was canceled. If a task was canceled, the contains an in its collection. + + -or- + An exception was thrown during the execution of at least one of the instances. - is a negative number other than -1 milliseconds, which represents an infinite time-out. - - -or- - + is a negative number other than -1 milliseconds, which represents an infinite time-out. + + -or- + is greater than Int32.MaxValue. The argument contains a null element. @@ -5158,19 +5178,19 @@ timeout is greater than if all of the instances completed execution within the allotted time; otherwise, . - noted above. - + noted above. + ]]> One or more of the objects in has been disposed. The argument is . - At least one of the instances was canceled. If a task was canceled, the contains an in its collection. - - -or- - + At least one of the instances was canceled. If a task was canceled, the contains an in its collection. + + -or- + An exception was thrown during the execution of at least one of the instances. is a negative number other than -1, which represents an infinite time-out. @@ -5238,14 +5258,14 @@ timeout is greater than Waits for any of the provided objects to complete execution. The index of the completed object in the array. - method then waits for any of the tasks to complete. The example displays the task ID of the task that ended the wait, as well as the current status of all the tasks. - + method then waits for any of the tasks to complete. The example displays the task ID of the task that ended the wait, as well as the current status of all the tasks. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WaitAny/WaitAny1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/System.Threading.Tasks.Task.WaitAny/vb/WaitAny1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/System.Threading.Tasks.Task.WaitAny/vb/WaitAny1.vb" id="Snippet1"::: + ]]> The has been disposed. @@ -5403,10 +5423,10 @@ timeout is greater than To be added. The has been disposed. The argument is . - The property of the argument is a negative number other than -1, which represents an infinite time-out. - - -or- - + The property of the argument is a negative number other than -1, which represents an infinite time-out. + + -or- + The property of the argument is greater than Int32.MaxValue. The argument contains a null element. @@ -5499,6 +5519,7 @@ timeout is greater than Gets a that will complete when this completes or when the specified has cancellation requested. The representing the asynchronous wait. It may or may not be the same instance as the current instance. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -5571,6 +5592,7 @@ timeout is greater than Gets a that will complete when this completes, when the specified timeout expires, or when the specified has cancellation requested. The representing the asynchronous wait. It may or may not be the same instance as the current instance. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -5626,30 +5648,30 @@ timeout is greater than Creates a task that will complete when all of the objects in an enumerable collection have completed. A task that represents the completion of all of the supplied tasks. - method that return a object are typically called when you are interested in the status of a set of tasks or in the exceptions thrown by a set of tasks. - + method that return a object are typically called when you are interested in the status of a set of tasks or in the exceptions thrown by a set of tasks. + > [!NOTE] -> The call to method does not block the calling thread. - - If any of the supplied tasks completes in a faulted state, the returned task will also complete in a state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. - - If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the state. - - If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the state. - - If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a state before it's returned to the caller. - - - -## Examples - The following example creates a set of tasks that ping the URLs in an array. The tasks are stored in a `List` collection that is passed to the method. After the call to the method ensures that all threads have completed, the example examines the property to determine whether any tasks have faulted. - +> The call to method does not block the calling thread. + + If any of the supplied tasks completes in a faulted state, the returned task will also complete in a state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. + + If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the state. + + If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the state. + + If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a state before it's returned to the caller. + + + +## Examples + The following example creates a set of tasks that ping the URLs in an array. The tasks are stored in a `List` collection that is passed to the method. After the call to the method ensures that all threads have completed, the example examines the property to determine whether any tasks have faulted. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WhenAll/WhenAll4.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/WhenAll4.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/WhenAll4.vb" id="Snippet4"::: + ]]> The argument was . @@ -5706,30 +5728,30 @@ timeout is greater than Creates a task that will complete when all of the objects in an array have completed. A task that represents the completion of all of the supplied tasks. - method that return a object are typically called when you are interested in the status of a set of tasks or in the exceptions thrown by a set of tasks. - + method that return a object are typically called when you are interested in the status of a set of tasks or in the exceptions thrown by a set of tasks. + > [!NOTE] -> The call to method does not block the calling thread. - - If any of the supplied tasks completes in a faulted state, the returned task will also complete in a state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. - - If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the state. - - If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the state. - - If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a state before it's returned to the caller. - - - -## Examples - The following example creates a set of tasks that ping the URLs in an array. The tasks are stored in a `List` collection that is converted to an array and passed to the method. After the call to the method ensures that all threads have completed, the example examines the property to determine whether any tasks have faulted. - +> The call to method does not block the calling thread. + + If any of the supplied tasks completes in a faulted state, the returned task will also complete in a state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. + + If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the state. + + If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the state. + + If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a state before it's returned to the caller. + + + +## Examples + The following example creates a set of tasks that ping the URLs in an array. The tasks are stored in a `List` collection that is converted to an array and passed to the method. After the call to the method ensures that all threads have completed, the example examines the property to determine whether any tasks have faulted. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WhenAll/WhenAll3.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/WhenAll3.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/WhenAll3.vb" id="Snippet3"::: + ]]> The argument was . @@ -5783,29 +5805,29 @@ timeout is greater than Creates a task that will complete when all of the objects in an enumerable collection have completed. A task that represents the completion of all of the supplied tasks. - method does not block the calling thread. However, a call to the returned property does block the calling thread. - - If any of the supplied tasks completes in a faulted state, the returned task will also complete in a state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. - - If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the state. - - If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the state. The property of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output task's property will return an `TResult[]` where `arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result)`. - - If the `tasks` argument contains no tasks, the returned task will immediately transition to a state before it's returned to the caller. The returned `TResult[]` will be an array of 0 elements. - - - -## Examples - The following example creates ten tasks, each of which instantiates a random number generator that creates 1,000 random numbers between 1 and 1,000 and computes their mean. The method is used to delay instantiation of the random number generators so that they are not created with identical seed values. The call to the method then returns an array that contains the mean computed by each task. These are then used to calculate the overall mean. - + method does not block the calling thread. However, a call to the returned property does block the calling thread. + + If any of the supplied tasks completes in a faulted state, the returned task will also complete in a state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. + + If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the state. + + If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the state. The property of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output task's property will return an `TResult[]` where `arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result)`. + + If the `tasks` argument contains no tasks, the returned task will immediately transition to a state before it's returned to the caller. The returned `TResult[]` will be an array of 0 elements. + + + +## Examples + The following example creates ten tasks, each of which instantiates a random number generator that creates 1,000 random numbers between 1 and 1,000 and computes their mean. The method is used to delay instantiation of the random number generators so that they are not created with identical seed values. The call to the method then returns an array that contains the mean computed by each task. These are then used to calculate the overall mean. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WhenAll/whenall1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/whenall1.vb" id="Snippet1"::: - - In this case, the ten individual tasks are stored in a object. implements the interface. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/whenall1.vb" id="Snippet1"::: + + In this case, the ten individual tasks are stored in a object. implements the interface. + ]]> The argument was . @@ -5866,27 +5888,27 @@ timeout is greater than Creates a task that will complete when all of the objects in an array have completed. A task that represents the completion of all of the supplied tasks. - method does not block the calling thread. However, a call to the returned property does block the calling thread. - - If any of the supplied tasks completes in a faulted state, the returned task will also complete in a state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. - - If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the state. - - If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the state. The of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output task's will return an `TResult[]` where `arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result)`. - - If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a state before it's returned to the caller. The returned `TResult[]` will be an array of 0 elements. - - - -## Examples - The following example creates ten tasks, each of which instantiates a random number generator that creates 1,000 random numbers between 1 and 1,000 and computes their mean. In this case, the ten individual tasks are stored in a `Task` array. The method is used to delay instantiation of the random number generators so that they are not created with identical seed values. The call to the method then returns an array that contains the mean computed by each task. These are then used to calculate the overall mean. - + method does not block the calling thread. However, a call to the returned property does block the calling thread. + + If any of the supplied tasks completes in a faulted state, the returned task will also complete in a state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. + + If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the state. + + If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the state. The of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output task's will return an `TResult[]` where `arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result)`. + + If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a state before it's returned to the caller. The returned `TResult[]` will be an array of 0 elements. + + + +## Examples + The following example creates ten tasks, each of which instantiates a random number generator that creates 1,000 random numbers between 1 and 1,000 and computes their mean. In this case, the ten individual tasks are stored in a `Task` array. The method is used to delay instantiation of the random number generators so that they are not created with identical seed values. The call to the method then returns an array that contains the mean computed by each task. These are then used to calculate the overall mean. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WhenAll/whenall2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/whenall2.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/whenall2.vb" id="Snippet2"::: + ]]> The argument was . @@ -5946,11 +5968,11 @@ timeout is greater than Creates a task that will complete when any of the supplied tasks have completed. A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed. - The argument was . @@ -6007,11 +6029,11 @@ timeout is greater than Creates a task that will complete when any of the supplied tasks have completed. A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed. - The argument was null. @@ -6113,11 +6135,11 @@ The returned task will complete when any of the supplied tasks has completed. T Creates a task that will complete when any of the supplied tasks have completed. A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed. - The argument was . @@ -6178,11 +6200,11 @@ The returned task will complete when any of the supplied tasks has completed. T Creates a task that will complete when any of the supplied tasks have completed. A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed. - The argument was null. @@ -6284,11 +6306,11 @@ The returned task will complete when any of the supplied tasks has completed. T Creates an awaitable task that asynchronously yields back to the current context when awaited. A context that, when awaited, will asynchronously transition back into the current context at the time of the await. If the current is non-null, it is treated as the current context. Otherwise, the task scheduler that is associated with the currently executing task is treated as the current context. - object), this will post the remainder of the method's execution back to that context. However, the context will decide how to prioritize this work relative to other work that may be pending. The synchronization context that is present on a UI thread in most UI environments will often prioritize work posted to the context higher than input and rendering work. For this reason, do not rely on `await Task.Yield();` to keep a UI responsive. For more information, see the entry [Useful Abstractions Enabled with ContinueWith](https://devblogs.microsoft.com/pfxteam/useful-abstractions-enabled-with-continuewith/) in the Parallel Programming with .NET blog. - + object), this will post the remainder of the method's execution back to that context. However, the context will decide how to prioritize this work relative to other work that may be pending. The synchronization context that is present on a UI thread in most UI environments will often prioritize work posted to the context higher than input and rendering work. For this reason, do not rely on `await Task.Yield();` to keep a UI responsive. For more information, see the entry [Useful Abstractions Enabled with ContinueWith](https://devblogs.microsoft.com/pfxteam/useful-abstractions-enabled-with-continuewith/) in the Parallel Programming with .NET blog. + ]]> diff --git a/xml/System.Threading.Tasks/TaskAsyncEnumerableExtensions.xml b/xml/System.Threading.Tasks/TaskAsyncEnumerableExtensions.xml index 8c8bba1f860..8a8b58dd099 100644 --- a/xml/System.Threading.Tasks/TaskAsyncEnumerableExtensions.xml +++ b/xml/System.Threading.Tasks/TaskAsyncEnumerableExtensions.xml @@ -184,6 +184,7 @@ This method is implemented by using deferred execution. The underlying + The cancellation token was canceled. This exception is stored into the returned task. @@ -229,6 +230,7 @@ This method is implemented by using deferred execution. The underlying Sets the to be passed to when iterating. The configured enumerable. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Threading.Tasks/TaskCanceledException.xml b/xml/System.Threading.Tasks/TaskCanceledException.xml index 4b75ae389cd..9946d3ff95e 100644 --- a/xml/System.Threading.Tasks/TaskCanceledException.xml +++ b/xml/System.Threading.Tasks/TaskCanceledException.xml @@ -104,18 +104,18 @@ Initializes a new instance of the class with a system-supplied message that describes the error. - property of the new instance to a system-supplied message that describes the error. This message takes into account the current system culture. - - The following table shows the initial property values for an instance of : - -|Property|Value| -|--------------|-----------| -||`null`.| -||The localized error message string.| - + property of the new instance to a system-supplied message that describes the error. This message takes into account the current system culture. + + The following table shows the initial property values for an instance of : + +|Property|Value| +|--------------|-----------| +||`null`.| +||The localized error message string.| + ]]> Handling and Throwing Exceptions @@ -164,16 +164,16 @@ The message that describes the exception. The caller of this constructor is required to ensure that this string has been localized for the current system culture. Initializes a new instance of the class with a specified message that describes the error. - . - -|Property|Value| -|--------------|-----------| -||`null`.| -||The error message string specified in `message`.| - + . + +|Property|Value| +|--------------|-----------| +||`null`.| +||The error message string specified in `message`.| + ]]> Handling and Throwing Exceptions @@ -267,11 +267,11 @@ The contextual information about the source or destination. Initializes a new instance of the class with serialized data. - Handling and Throwing Exceptions @@ -323,18 +323,18 @@ The exception that is the cause of the current exception. If the parameter is not , the current exception is raised in a block that handles the inner exception. Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - property. The property returns the same value that is passed into the constructor, or `null` if the property does not supply the inner exception value to the constructor. - - The following table shows the initial property values for an instance of . - -|Property|Value| -|--------------|-----------| -||`null`.| -||The error message string specified in `message`.| - + property. The property returns the same value that is passed into the constructor, or `null` if the property does not supply the inner exception value to the constructor. + + The following table shows the initial property values for an instance of . + +|Property|Value| +|--------------|-----------| +||`null`.| +||The error message string specified in `message`.| + ]]> Handling and Throwing Exceptions @@ -381,6 +381,7 @@ The cancellation token that triggered the cancellation. Initializes a new instance of the class with a specified error message, a reference to the inner exception that is the cause of this exception, and the that triggered the cancellation. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -423,13 +424,13 @@ Gets the task associated with this exception. A reference to the that is associated with this exception. - , in which case this property will return null. - - This property is thread-safe and may be used from multiple threads concurrently. - + , in which case this property will return null. + + This property is thread-safe and may be used from multiple threads concurrently. + ]]> Handling and Throwing Exceptions diff --git a/xml/System.Threading.Tasks/TaskCompletionSource.xml b/xml/System.Threading.Tasks/TaskCompletionSource.xml index 76e509a219d..c1aed2b2bd6 100644 --- a/xml/System.Threading.Tasks/TaskCompletionSource.xml +++ b/xml/System.Threading.Tasks/TaskCompletionSource.xml @@ -25,7 +25,7 @@ It is often the case that a is desired to represent another asynchronous operation. is provided for this purpose. It enables the creation of a task that can be handed out to consumers, and those consumers can use the members of the task as they would any other. However, unlike most tasks, the state of a task created by a is controlled explicitly by the methods on . This enables the completion of the external asynchronous operation to be propagated to the underlying `Task`. The separation also ensures that consumers are not able to transition the state without access to the corresponding . All members of are thread-safe and may be used from multiple threads concurrently. - + ]]> @@ -182,6 +182,7 @@ The created by this instance and accessible t Transitions the underlying into the state using the specified token. To be added. The underlying is already in one of the three final states: , , or . + The cancellation token was canceled. This exception is stored into the returned task. @@ -368,6 +369,7 @@ This operation will return `false` if the is ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Threading.Tasks/TaskCompletionSource`1.xml b/xml/System.Threading.Tasks/TaskCompletionSource`1.xml index fd7fd7c5de7..12c0b48e6f0 100644 --- a/xml/System.Threading.Tasks/TaskCompletionSource`1.xml +++ b/xml/System.Threading.Tasks/TaskCompletionSource`1.xml @@ -49,21 +49,21 @@ The type of the result value associated with this . Represents the producer side of a unbound to a delegate, providing access to the consumer side through the property. - to represent an external asynchronous operation. is provided for this purpose. It enables the creation of a task that can be handed out to consumers. The consumers can use the members of the task the same way as they would in any other scenario handling task member variables. However, unlike most tasks, the state of a task created by a TaskCompletionSource is controlled explicitly by the methods on TaskCompletionSource. This enables the completion of the external asynchronous operation to be propagated to the underlying Task. The separation also ensures that consumers are not able to transition the state without access to the corresponding TaskCompletionSource. For more information, see the entry [The Nature of TaskCompletionSource\](https://devblogs.microsoft.com/pfxteam/the-nature-of-taskcompletionsourcetresult/) in the Parallel Programming with .NET blog. - - The [Parallel Extensions samples](https://go.microsoft.com/fwlink/?LinkID=165717) also contain examples of how to use . - - - -## Examples - The following example shows how to use a : - + to represent an external asynchronous operation. is provided for this purpose. It enables the creation of a task that can be handed out to consumers. The consumers can use the members of the task the same way as they would in any other scenario handling task member variables. However, unlike most tasks, the state of a task created by a TaskCompletionSource is controlled explicitly by the methods on TaskCompletionSource. This enables the completion of the external asynchronous operation to be propagated to the underlying Task. The separation also ensures that consumers are not able to transition the state without access to the corresponding TaskCompletionSource. For more information, see the entry [The Nature of TaskCompletionSource\](https://devblogs.microsoft.com/pfxteam/the-nature-of-taskcompletionsourcetresult/) in the Parallel Programming with .NET blog. + + The [Parallel Extensions samples](https://go.microsoft.com/fwlink/?LinkID=165717) also contain examples of how to use . + + + +## Examples + The following example shows how to use a : + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskCompletionSourceTResult/Overview/taskcompletionsource.cs" id="Snippet01"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskcompletionsource/vb/taskcompletionsource.vb" id="Snippet01"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskcompletionsource/vb/taskcompletionsource.vb" id="Snippet01"::: + ]]> All members of are thread-safe and may be used from multiple threads concurrently. @@ -204,11 +204,11 @@ The options to use when creating the underlying . Creates a with the specified options. - created by this instance and accessible through its property will be instantiated using the specified `creationOptions`. - + created by this instance and accessible through its property will be instantiated using the specified `creationOptions`. + ]]> The represent options invalid for use with a . @@ -344,6 +344,7 @@ Transitions the underlying into the state using the specified token. To be added. The underlying is already in one of the three final states: , , or . + The cancellation token was canceled. This exception is stored into the returned task. @@ -543,13 +544,13 @@ Gets the created by this . Returns the created by this . - that is controlled by this instance. When you create a object, the property of this object returns - - The , , , and methods (and their "Try" variants) on this instance all result in the relevant state transitions on this underlying Task. - + that is controlled by this instance. When you create a object, the property of this object returns + + The , , , and methods (and their "Try" variants) on this instance all result in the relevant state transitions on this underlying Task. + ]]> Using TPL with Other Asynchronous Patterns @@ -609,13 +610,13 @@ if the operation was successful; false if the operation was unsuccessful or the object has already been disposed. - is already in one of the three final states: , , or . - - This method also returns false if the underlying has already been disposed. - + is already in one of the three final states: , , or . + + This method also returns false if the underlying has already been disposed. + ]]> Using TPL with Other Asynchronous Patterns @@ -666,21 +667,22 @@ if the operation is successful; otherwise, . - object is already in one of the following three final states. - -- - -- - -- - - This method also returns `false` if the underlying object has already been disposed. - + object is already in one of the following three final states. + +- + +- + +- + + This method also returns `false` if the underlying object has already been disposed. + ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -738,19 +740,19 @@ if the operation was successful; otherwise, . - is already in one of the three final states: , , or . - + is already in one of the three final states: , , or . + ]]> The was disposed. The argument is . - There are one or more null elements in . - - -or- - + There are one or more null elements in . + + -or- + The collection is empty. Using TPL with Other Asynchronous Patterns How to: Wrap EAP Patterns in a Task @@ -800,11 +802,11 @@ if the operation was successful; otherwise, . - is already in one of the three final states: , , or . - + is already in one of the three final states: , , or . + ]]> The was disposed. @@ -857,13 +859,13 @@ if the operation was successful; otherwise, . - is already in one of the three final states: , , or . - - This method also returns false if the underlying has already been disposed. - + is already in one of the three final states: , , or . + + This method also returns false if the underlying has already been disposed. + ]]> Using TPL with Other Asynchronous Patterns diff --git a/xml/System.Threading.Tasks/TaskFactory.xml b/xml/System.Threading.Tasks/TaskFactory.xml index 9e2d894fc54..71316dcda88 100644 --- a/xml/System.Threading.Tasks/TaskFactory.xml +++ b/xml/System.Threading.Tasks/TaskFactory.xml @@ -48,43 +48,43 @@ Provides support for creating and scheduling objects. - class, which creates and objects. You can call the overloads of this method to create and execute a task that requires non-default arguments. - + class, which creates and objects. You can call the overloads of this method to create and execute a task that requires non-default arguments. + > [!WARNING] - > Starting with .NET Framework 4.5, the method provides the easiest way to create a task with default configuration values and start it immediately. - -- The class, which creates objects. - - The class allows you to do the following: - -- Create a task and start it immediately by calling the method. - + > Starting with .NET Framework 4.5, the method provides the easiest way to create a task with default configuration values and start it immediately. + +- The class, which creates objects. + + The class allows you to do the following: + +- Create a task and start it immediately by calling the method. + > [!WARNING] - > Starting with .NET Framework 4.5, the method provides the easiest way to create a task with default configuration values and start it immediately. - -- Create a task that starts when any one of the tasks in an array has completed by calling the method. - -- Create a task that starts when all the tasks in an array have completed by calling the method. - - The static property returns a default object. You can also call one of the class constructors to configure the objects that the class creates. The following example configures a new object to create tasks that have a specified cancellation token, task creation options, continuation options, and a customized task scheduler. - + > Starting with .NET Framework 4.5, the method provides the easiest way to create a task with default configuration values and start it immediately. + +- Create a task that starts when any one of the tasks in an array has completed by calling the method. + +- Create a task that starts when all the tasks in an array have completed by calling the method. + + The static property returns a default object. You can also call one of the class constructors to configure the objects that the class creates. The following example configures a new object to create tasks that have a specified cancellation token, task creation options, continuation options, and a customized task scheduler. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskFactory/Overview/program.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/tpl_factories/vb/factories_vb.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/tpl_factories/vb/factories_vb.vb" id="Snippet1"::: + In most cases, you do not have to instantiate a new instance. Instead, you can use the property, which returns a factory object that uses default values. You can then call its methods to start new tasks or define task continuations. For an illustration, see the example. - -## Examples - The following example uses the static property to make two calls to the method. The first populates an array with the names of files in the user's MyDocuments directory, while the second populates an array with the names of subdirectories of the user's MyDocuments directory. It then calls the method, which displays information about the number of files and directories in the two arrays after the first two tasks have completed execution. - + +## Examples + The following example uses the static property to make two calls to the method. The first populates an array with the names of files in the user's MyDocuments directory, while the second populates an array with the names of subdirectories of the user's MyDocuments directory. It then calls the method, which displays information about the number of files and directories in the two arrays after the first two tasks have completed execution. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Factory/factory1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.factory/vb/factory1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.factory/vb/factory1.vb" id="Snippet1"::: + ]]> All public and protected members of are thread-safe and may be used concurrently from multiple threads. @@ -138,11 +138,11 @@ Initializes a instance with the default configuration. - instance with a default configuration. The property is initialized to , the property is initialized to , and the property is initialized to the current scheduler (see ). - + instance with a default configuration. The property is initialized to , the property is initialized to , and the property is initialized to the current scheduler (see ). + ]]> Task Parallel Library (TPL) @@ -187,15 +187,16 @@ The that will be assigned to tasks created by this unless another CancellationToken is explicitly specified while calling the factory methods. Initializes a instance with the specified configuration. - instance with a default configuration. The property is initialized to , the property is initialized to , and the property is initialized to the current scheduler (see ). - + instance with a default configuration. The property is initialized to , the property is initialized to , and the property is initialized to the current scheduler (see ). + ]]> Task Parallel Library (TPL) Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -238,11 +239,11 @@ The to use to schedule any tasks created with this TaskFactory. A null value indicates that the current TaskScheduler should be used. Initializes a instance with the specified configuration. - property is initialized to , the property is initialized to , and the property is initialized to `scheduler`, unless it's null, in which case the property is initialized to the current scheduler (see ). - + property is initialized to , the property is initialized to , and the property is initialized to `scheduler`, unless it's null, in which case the property is initialized to the current scheduler (see ). + ]]> @@ -291,17 +292,17 @@ The default to use when creating continuation tasks with this TaskFactory. Initializes a instance with the specified configuration. - property is initialized to `creationOptions`, the property is initialized to `continuationOptions`, and the property is initialized to the current scheduler (see ). - + property is initialized to `creationOptions`, the property is initialized to `continuationOptions`, and the property is initialized to the current scheduler (see ). + ]]> - The argument specifies an invalid value. For more information, see the Remarks for . - - -or- - + The argument specifies an invalid value. For more information, see the Remarks for . + + -or- + The argument specifies an invalid value. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -353,20 +354,21 @@ The default to use to schedule any Tasks created with this TaskFactory. A null value indicates that TaskScheduler.Current should be used. Initializes a instance with the specified configuration. - property is initialized to `creationOptions`, the property is initialized to `continuationOptions`, and the property is initialized to `scheduler`, unless it's null, in which case the property is initialized to the current scheduler (see ). - + property is initialized to `creationOptions`, the property is initialized to `continuationOptions`, and the property is initialized to `scheduler`, unless it's null, in which case the property is initialized to the current scheduler (see ). + ]]> - The argument specifies an invalid value. For more information, see the Remarks for . - - -or- - + The argument specifies an invalid value. For more information, see the Remarks for . + + -or- + The argument specifies an invalid value. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -408,11 +410,11 @@ Gets the default cancellation token for this task factory. The default task cancellation token for this task factory. - that will be assigned to all tasks created by this factory, unless another value is explicitly specified during the call to the factory methods. - + that will be assigned to all tasks created by this factory, unless another value is explicitly specified during the call to the factory methods. + ]]> Task Parallel Library (TPL) @@ -459,11 +461,11 @@ Gets the default task continuation options for this task factory. The default task continuation options for this task factory. - Task Parallel Library (TPL) @@ -526,30 +528,30 @@ Creates a continuation task that starts when a set of specified tasks has completed. The new continuation task. - method executes the `continuationAction` delegate when all tasks in the `tasks` array have completed, regardless of their completion status. - - Exceptions thrown by tasks in the `tasks` array are not available to the continuation task through structured exception handling. You can determine which exceptions were thrown by examining the property of each task in the `tasks` array. To use structured exception handling to handle exceptions thrown by tasks in the `tasks` array, call the method. - - - -## Examples - The following example launches separate tasks that use a regular expression to count the number of words in a set of text files. The method is used to launch a task that displays the total word count when all the antecedent tasks have completed. - + method executes the `continuationAction` delegate when all tasks in the `tasks` array have completed, regardless of their completion status. + + Exceptions thrown by tasks in the `tasks` array are not available to the continuation task through structured exception handling. You can determine which exceptions were thrown by examining the property of each task in the `tasks` array. To use structured exception handling to handle exceptions thrown by tasks in the `tasks` array, call the method. + + + +## Examples + The following example launches separate tasks that use a regular expression to count the number of words in a set of text files. The method is used to launch a task that displays the total word count when all the antecedent tasks have completed. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskFactory/ContinueWhenAll/continuewhenall1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.continuewhenall/vb/continuewhenall1.vb" id="Snippet1"::: - - The call to the continuation task's method does not allow it to handle exceptions thrown by the antecedent tasks, so the example examines the property of each antecedent task to determine whether the task succeeded. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.continuewhenall/vb/continuewhenall1.vb" id="Snippet1"::: + + The call to the continuation task's method does not allow it to handle exceptions thrown by the antecedent tasks, so the example examines the property of each antecedent task to determine whether the task succeeded. + ]]> An element in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) @@ -603,34 +605,35 @@ Creates a continuation task that starts when a set of specified tasks has completed. The new continuation task. - exception and displays an error message. - +The following example creates a cancellation token, which it passes to separate tasks that use a regular expression to count the number of words in a set of text files. The cancellation token is set if a file cannot be found. The `ContinueWhenAll(Task[], Action{Task[]}, CancellationToken)` method is used to launch a task that displays the total word count when all the antecedent tasks have completed. If the cancellation token is set, which indicates that one or more tasks have been cancelled, it handles the exception and displays an error message. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskFactory/ContinueWhenAll/continuewhenall2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.continuewhenall/vb/continuewhenall2.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.continuewhenall/vb/continuewhenall2.vb" id="Snippet2"::: + ]]> - An element in the array has been disposed. - - -or- - + An element in the array has been disposed. + + -or- + The that created has already been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -689,10 +692,10 @@ The NotOn\* and OnlyOn\* , ]]> An element in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The argument specifies an invalid value. The array is empty or contains a null value. @@ -759,14 +762,14 @@ The NotOn\* and OnlyOn\* , ]]> - The array is . - - -or- - - The argument is . - - -or- - + The array is . + + -or- + + The argument is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) @@ -774,6 +777,7 @@ The NotOn\* and OnlyOn\* , specifies an invalid value. The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -826,10 +830,10 @@ The NotOn\* and OnlyOn\* , The new continuation task. To be added. An element in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) @@ -888,20 +892,21 @@ The NotOn\* and OnlyOn\* , Creates a continuation task that starts when a set of specified tasks has completed. The new continuation task. To be added. - An element in the array has been disposed. - - -or- - + An element in the array has been disposed. + + -or- + The that created has already been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -964,10 +969,10 @@ The NotOn\* and OnlyOn\* , ]]> An element in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The argument specifies an invalid value. The array is empty or contains a null value. @@ -1039,14 +1044,14 @@ The NotOn\* and OnlyOn\* , ]]> - The array is . - - -or- - - The argument is . - - -or- - + The array is . + + -or- + + The argument is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) @@ -1055,6 +1060,7 @@ The NotOn\* and OnlyOn\* , specifies an invalid value. The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1107,10 +1113,10 @@ The NotOn\* and OnlyOn\* , The new continuation task. To be added. An element in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) @@ -1168,20 +1174,21 @@ The NotOn\* and OnlyOn\* , Creates a continuation task that starts when a set of specified tasks has completed. The new continuation task. To be added. - An element in the array has been disposed. - - -or- - + An element in the array has been disposed. + + -or- + The that created has already been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1244,10 +1251,10 @@ The NotOn\* and OnlyOn\* , ]]> An element in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The argument specifies an invalid value. The array is empty or contains a null value. @@ -1319,14 +1326,14 @@ The NotOn\* and OnlyOn\* , ]]> - The array is . - - -or- - - The argument is . - - -or- - + The array is . + + -or- + + The argument is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) @@ -1335,6 +1342,7 @@ The NotOn\* and OnlyOn\* , specifies an invalid value. The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1389,10 +1397,10 @@ The NotOn\* and OnlyOn\* , The new continuation task. To be added. An element in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) @@ -1453,20 +1461,21 @@ The NotOn\* and OnlyOn\* , Creates a continuation task that starts when a set of specified tasks has completed. The new continuation task. To be added. - An element in the array has been disposed. - - -or- - + An element in the array has been disposed. + + -or- + The that created has already been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array is empty or contains a null value. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1531,10 +1540,10 @@ The NotOn\* and OnlyOn\* , ]]> An element in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The argument specifies an invalid value. The array is empty or contains a null value. @@ -1608,25 +1617,26 @@ The NotOn\* and OnlyOn\* , ]]> - The array is . - - -or- - - The argument is . - - -or- - + The array is . + + -or- + + The argument is . + + -or- + The argument is . The array is empty or contains a null value. The argument specifies an invalid value. - An element in the array has been disposed. - - -or- - + An element in the array has been disposed. + + -or- + The that created has already been disposed. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1688,26 +1698,26 @@ The NotOn\* and OnlyOn\* , Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . - One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -1761,24 +1771,25 @@ The NotOn\* and OnlyOn\* , Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . To be added. - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + has already been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty . Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1828,26 +1839,26 @@ The NotOn\* and OnlyOn\* , Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . - , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. - + + The NotOn\* and OnlyOn\* , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + is . specifies an invalid TaskContinuationOptions value. - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -1913,19 +1924,19 @@ The NotOn\* and OnlyOn\* , ]]> - The array is . - - -or- - - is . - - -or- - + The array is . + + -or- + + is . + + -or- + is . - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty. specifies an invalid TaskContinuationOptions value. @@ -1933,6 +1944,7 @@ The NotOn\* and OnlyOn\* , Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1985,15 +1997,15 @@ The NotOn\* and OnlyOn\* , The new continuation . To be added. One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + is . - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -2051,24 +2063,25 @@ The NotOn\* and OnlyOn\* , Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . To be added. - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The provided has already been disposed. - The array is . - - -or- - + The array is . + + -or- + is . - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -2122,26 +2135,26 @@ The array is empty. Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . - , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. - The NotOn\* and OnlyOn\* , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. - ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + is . specifies an invalid TaskContinuationOptions value. - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -2203,27 +2216,27 @@ The array is empty. Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . - , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. - + + The NotOn\* and OnlyOn\* , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. + ]]> - The array is . - - -or- - - is . - - -or- - + The array is . + + -or- + + is . + + -or- + paramref name="scheduler" /> is . - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty. specifies an invalid value. @@ -2231,6 +2244,7 @@ The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -2283,15 +2297,15 @@ The array is empty. The new continuation . To be added. One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + is . - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -2349,24 +2363,25 @@ The array is empty. Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . To be added. - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The provided has already been disposed. - The array is . - - -or- - + The array is . + + -or- + is . - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -2420,26 +2435,26 @@ The array is empty. Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . - , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. - +The NotOn\* and OnlyOn\* , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + is . specifies an invalid TaskContinuationOptions value. - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -2501,27 +2516,27 @@ The NotOn\* and OnlyOn\* , Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . - , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. ]]> - The array is . - - -or- - - is . - - -or- - + The array is . + + -or- + + is . + + -or- + is . - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty. specifies an invalid TaskContinuationOptions value. @@ -2529,6 +2544,7 @@ The NotOn\* and OnlyOn\* , Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -2583,15 +2599,15 @@ The NotOn\* and OnlyOn\* , The new continuation . To be added. One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + is . - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -2651,24 +2667,25 @@ The NotOn\* and OnlyOn\* , Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . To be added. - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The provided has already been disposed. - The array is . - - -or- - + The array is . + + -or- + is . - The array contains a value. - - -or- - + The array contains a value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -2724,26 +2741,26 @@ The array is empty. Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . - , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. - + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + is . specifies an invalid TaskContinuationOptions value. - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -2807,27 +2824,27 @@ The NotOn\* and OnlyOn\* , Creates a continuation that will be started upon the completion of any Task in the provided set. The new continuation . - , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. - +The NotOn\* and OnlyOn\* , which constrain for which states a continuation will be executed, are illegal with `ContinueWhenAny`. + ]]> - The array is . - - -or- - - is . - - -or- - + The array is . + + -or- + + is . + + -or- + is . - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -2835,6 +2852,7 @@ The NotOn\* and OnlyOn\* , specifies an invalid TaskContinuationOptions value. The provided has already been disposed. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2876,11 +2894,11 @@ The NotOn\* and OnlyOn\* , Gets the default task creation options for this task factory. The default task creation options for this task factory. - Task Parallel Library (TPL) @@ -2943,20 +2961,20 @@ The NotOn\* and OnlyOn\* , Creates a that executes an end method action when a specified completes. A that represents the asynchronous operation. - [!TIP] -> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. - +> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. + ]]> - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -3010,18 +3028,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -3074,20 +3092,20 @@ The NotOn\* and OnlyOn\* , Creates a that executes an end method action when a specified completes. A that represents the asynchronous operation. - [!TIP] -> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. - +> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. + ]]> - is . - - -or- - + is . + + -or- + is . paramref name="creationOptions" /> specifies an invalid value. For more information, see the Remarks for Task Parallel Library (TPL) @@ -3144,18 +3162,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. The values , and are all mutually exclusive. In the FromAsync methods, either `LongRunning` or `AttachedToParent` by themselves will cause an to be thrown. - + is running on. This method throws any exceptions thrown by the `beginMethod`. The values , and are all mutually exclusive. In the FromAsync methods, either `LongRunning` or `AttachedToParent` by themselves will cause an to be thrown. + ]]> - is . - - -or- - + is . + + -or- + is . specifies an invalid TaskCreationOptions value. @@ -3212,24 +3230,24 @@ The NotOn\* and OnlyOn\* , Creates a that executes an end method action when a specified completes. The created that represents the asynchronous operation. - [!TIP] -> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. - +> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. + ]]> - is . - - -or- - - is . - - -or- - + is . + + -or- + + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -3291,18 +3309,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -3364,18 +3382,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -3432,20 +3450,20 @@ The NotOn\* and OnlyOn\* , Creates a that executes an end method function when a specified completes. A that represents the asynchronous operation. - [!TIP] -> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. - +> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. + ]]> - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -3504,18 +3522,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -3572,20 +3590,20 @@ The NotOn\* and OnlyOn\* , Creates a that executes an end method function when a specified completes. A that represents the asynchronous operation. - [!TIP] -> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. - +> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. + ]]> - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -3647,18 +3665,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -3719,24 +3737,24 @@ The NotOn\* and OnlyOn\* , Creates a that executes an end method function when a specified completes. A that represents the asynchronous operation. - [!TIP] -> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. - +> The overloads that take an `asyncResult` parameter are not as efficient as the overloads that take a `beginMethod` parameter. If performance is an issue, use the overloads that provide the `beginMethod`/`endMethod` pattern. + ]]> - is . - - -or- - - is . - - -or- - + is . + + -or- + + is . + + -or- + is . specifies an invalid TaskCreationOptions value. For more information, see the Remarks for @@ -3802,18 +3820,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -3879,18 +3897,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -3954,18 +3972,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -4029,18 +4047,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -4110,18 +4128,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -4191,18 +4209,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -4270,18 +4288,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -4349,18 +4367,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -4432,18 +4450,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -4515,18 +4533,18 @@ The NotOn\* and OnlyOn\* , Creates a that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - is running on. This method throws any exceptions thrown by the `beginMethod`. - + is running on. This method throws any exceptions thrown by the `beginMethod`. + ]]> - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -4574,13 +4592,13 @@ The NotOn\* and OnlyOn\* , Gets the default task scheduler for this task factory. The default task scheduler for this task factory. - property is used. - + property is used. + ]]> @@ -4596,17 +4614,17 @@ The NotOn\* and OnlyOn\* , Creates and starts a task. - method is the recommended way to launch a compute-bound task. Use the method only when you require fine-grained control for a long-running, compute-bound task. This includes scenarios in which you want to control the following: - -- Task creation options. Tasks created by the method by default are created with the option. To override this behavior, or to provide other options, call a overload. - -- Parameter passing. The overloads of the method do not allow you to pass a parameter to the task delegate. Overloads of the method do. - + method is the recommended way to launch a compute-bound task. Use the method only when you require fine-grained control for a long-running, compute-bound task. This includes scenarios in which you want to control the following: + +- Task creation options. Tasks created by the method by default are created with the option. To override this behavior, or to provide other options, call a overload. + +- Parameter passing. The overloads of the method do not allow you to pass a parameter to the task delegate. Overloads of the method do. + - The task scheduler. The overloads of the method use the default task scheduler. To control the task scheduler, call a overload with a `scheduler` parameter. For more information, see . - + ]]> Samples for Parallel Programming with the .NET Core and .NET Standard @@ -4655,21 +4673,21 @@ The NotOn\* and OnlyOn\* , Creates and starts a task for the specified action delegate. The started task. - is functionally equivalent to creating a task by using one of its constructors, and then calling the method to schedule the task for execution. - - Starting with the .NET Framework 4.5, you can use the method as a quick way to call with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : by default does not allow child tasks started with the option to attach to the current instance, whereas does. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - - - -## Examples - The following example uses the method to repeatedly invoke an delegate that generates a random number, interprets it as a Unicode code point, converts it to a UTF16-encoded code unit, and displays information about the resulting character or characters. - + is functionally equivalent to creating a task by using one of its constructors, and then calling the method to schedule the task for execution. + + Starting with the .NET Framework 4.5, you can use the method as a quick way to call with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : by default does not allow child tasks started with the option to attach to the current instance, whereas does. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + + + +## Examples + The following example uses the method to repeatedly invoke an delegate that generates a random number, interprets it as a Unicode code point, converts it to a UTF16-encoded code unit, and displays information about the resulting character or characters. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskFactory/StartNew/startnew1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskfactory.startnew/vb/startnew1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskfactory.startnew/vb/startnew1.vb" id="Snippet1"::: + ]]> The argument is . @@ -4723,21 +4741,21 @@ The NotOn\* and OnlyOn\* , Creates and starts a task for the specified action delegate and cancellation token. The started task. - to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method as a quick way to call with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : by default does not allow child tasks started with the option to attach to the current instance, whereas does. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - - - -## Examples - The following example calls the method to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the method to add information about each file to a object. Each detached nested task invoked by the loop checks the state of the cancellation token and, if cancellation is requested, calls the method. The method throws an exception that is handled in a `catch` block when the calling thread calls the method. - + to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method as a quick way to call with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : by default does not allow child tasks started with the option to attach to the current instance, whereas does. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + + + +## Examples + The following example calls the method to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the method to add information about each file to a object. Each detached nested task invoked by the loop checks the state of the cancellation token and, if cancellation is requested, calls the method. The method throws an exception that is handled in a `catch` block when the calling thread calls the method. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskFactory/StartNew/startnew2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskfactory.startnew/vb/startnew2.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskfactory.startnew/vb/startnew2.vb" id="Snippet2"::: + ]]> The provided has already been disposed. @@ -4746,6 +4764,7 @@ The NotOn\* and OnlyOn\* , Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -4793,13 +4812,13 @@ The NotOn\* and OnlyOn\* , Creates and starts a task for the specified action delegate and creation options. The started task. - to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> @@ -4857,23 +4876,23 @@ The NotOn\* and OnlyOn\* , Creates and starts a task for the specified action delegate and state. The started task. - is functionally equivalent to creating a using one of its constructors and then calling the method to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - - - -## Examples - The following example defines an array of 6-letter words. Each word is then passed to an delegate, which scrambles the word and displays the original word and its scrambled version. - + is functionally equivalent to creating a using one of its constructors and then calling the method to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + + + +## Examples + The following example defines an array of 6-letter words. Each word is then passed to an delegate, which scrambles the word and displays the original word and its scrambled version. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskFactory/StartNew/startnew3.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskfactory.startnew/vb/startnew3.vb" id="Snippet3"::: - - Note that the example initializes a single random number generator, which is protected by a lock. For the need of a lock, see "The System.Random class and thread safety" in the class topic. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskfactory.startnew/vb/startnew3.vb" id="Snippet3"::: + + Note that the example initializes a single random number generator, which is protected by a lock. For the need of a lock, see "The System.Random class and thread safety" in the class topic. + ]]> The argument is . @@ -4930,23 +4949,23 @@ The NotOn\* and OnlyOn\* , Creates and starts a task for the specified action delegate, state and cancellation token. The started task. - to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - - - -## Examples - The following example defines an array of 6-letter words. Each word is then passed to an delegate, which scrambles the word and displays the original word and its scrambled version. - + to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + + + +## Examples + The following example defines an array of 6-letter words. Each word is then passed to an delegate, which scrambles the word and displays the original word and its scrambled version. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskFactory/StartNew/startnew4.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskfactory.startnew/vb/startnew4.vb" id="Snippet4"::: - - Note that the example initializes a single random number generator, which is protected by a lock. For the need of a lock, see "The System.Random class and thread safety" in the class topic. To handle the possibility of corruption of the random number generator, a cancellation token is passed to task. If two random numbers equal zero, the method assumes that the random number generator is corrupted and sets the cancellation token. Before sorting the `chars` array that contains the six characters in a word, the method calls the method to throw an if the token has been canceled. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.taskfactory.startnew/vb/startnew4.vb" id="Snippet4"::: + + Note that the example initializes a single random number generator, which is protected by a lock. For the need of a lock, see "The System.Random class and thread safety" in the class topic. To handle the possibility of corruption of the random number generator, a cancellation token is passed to task. If two random numbers equal zero, the method assumes that the random number generator is corrupted and sets the cancellation token. Before sorting the `chars` array that contains the six characters in a word, the method calls the method to throw an if the token has been canceled. + ]]> The provided has already been disposed. @@ -4955,6 +4974,7 @@ The NotOn\* and OnlyOn\* , Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -5005,13 +5025,13 @@ The NotOn\* and OnlyOn\* , Creates and starts a task for the specified action delegate, state and creation options. The started task. - to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> @@ -5072,27 +5092,28 @@ The NotOn\* and OnlyOn\* , Creates and starts a task for the specified action delegate, cancellation token, creation options and state. The started task. - to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> The provided has already been disposed. - is . - - -or- - + is . + + -or- + is . specifies an invalid TaskCreationOptions value. For more information, see the Remarks for Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -5147,19 +5168,19 @@ The NotOn\* and OnlyOn\* , Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler. The started task. - to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see [Task.Run vs Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> The provided has already been disposed. - is . - + is . + -or- is . @@ -5168,6 +5189,7 @@ The NotOn\* and OnlyOn\* , Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -5217,21 +5239,21 @@ The NotOn\* and OnlyOn\* , Creates and starts a task of type for the specified function delegate. The started task. - is functionally equivalent to creating a using one of its constructors and then calling to schedule it for execution. - - Starting with the .NET Framework 4.5, you can call the method as a quick way to call with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : by default does not allow child tasks started with the option to attach to the current instance, whereas does. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - - - -## Examples - The following example is a simple addition app that generates two random numbers and prompts the user to enter their sum. It then indicates whether the answer is correct or, if the user's response is not a valid number, prompts the user to re-enter a valid number. The is used to create the objects that return the random numbers to add. - + is functionally equivalent to creating a using one of its constructors and then calling to schedule it for execution. + + Starting with the .NET Framework 4.5, you can call the method as a quick way to call with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : by default does not allow child tasks started with the option to attach to the current instance, whereas does. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + + + +## Examples + The following example is a simple addition app that generates two random numbers and prompts the user to enter their sum. It then indicates whether the answer is correct or, if the user's response is not a valid number, prompts the user to re-enter a valid number. The is used to create the objects that return the random numbers to add. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run5.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run5.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run5.vb" id="Snippet5"::: + ]]> The argument is . @@ -5290,13 +5312,13 @@ The NotOn\* and OnlyOn\* , Creates and starts a task of type for the specified function delegate and state. The started task. - using one of its constructors and then calling to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + using one of its constructors and then calling to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> @@ -5355,21 +5377,21 @@ The NotOn\* and OnlyOn\* , Creates and starts a task of type for the specified function delegate and cancellation token. The started task. - is functionally equivalent to creating a using one of its constructors and then calling to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method as a quick way to call with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : by default does not allow child tasks started with the option to attach to the current instance, whereas does. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - - - -## Examples - The following example uses two tasks to compute the Fibonacci sequence ending in F100 = F100-1 + F100-2 with seed values F1= 1, F2 = 1 and F1 = 0, F2= 1. Approximately half of the time, a cancellation token is set as the operations execute. The output from the example shows the result if the two tasks complete successfully and if the token is cancelled. - + is functionally equivalent to creating a using one of its constructors and then calling to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method as a quick way to call with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : by default does not allow child tasks started with the option to attach to the current instance, whereas does. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + + + +## Examples + The following example uses two tasks to compute the Fibonacci sequence ending in F100 = F100-1 + F100-2 with seed values F1= 1, F2 = 1 and F1 = 0, F2= 1. Approximately half of the time, a cancellation token is set as the operations execute. The output from the example shows the result if the two tasks complete successfully and if the token is cancelled. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/Run9.cs" id="Snippet9"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run9.vb" id="Snippet9"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run9.vb" id="Snippet9"::: + ]]> The provided has already been disposed. @@ -5378,6 +5400,7 @@ The NotOn\* and OnlyOn\* , Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -5429,13 +5452,13 @@ The NotOn\* and OnlyOn\* , Creates and starts a task of type for the specified function delegate and creation options. The started task. - using one of its constructors and then calling to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + using one of its constructors and then calling to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> @@ -5499,13 +5522,13 @@ The NotOn\* and OnlyOn\* , Creates and starts a task of type for the specified function delegate, state and cancellation token. The started task. - using one of its constructors and then calling to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + using one of its constructors and then calling to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> The provided has already been disposed. @@ -5514,6 +5537,7 @@ The NotOn\* and OnlyOn\* , Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -5568,13 +5592,13 @@ The NotOn\* and OnlyOn\* , Creates and starts a task of type for the specified function delegate, state and creation options. The started task. - using one of its constructors and then calling to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + using one of its constructors and then calling to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> @@ -5639,27 +5663,28 @@ The NotOn\* and OnlyOn\* , Creates and starts a task of type for the specified function delegate, cancellation token, creation options and task scheduler. The started task. - using one of its constructors and then calling to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + using one of its constructors and then calling to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> The provided has already been disposed. - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -5718,21 +5743,21 @@ The NotOn\* and OnlyOn\* , Creates and starts a task of type for the specified function delegate, state, cancellation token, creation options and task scheduler. The started task. - using one of its constructors and then calling to schedule it for execution. - - Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. - + using one of its constructors and then calling to schedule it for execution. + + Starting with the .NET Framework 4.5, you can use the method with an object as a quick way to call with default parameters. For more information and code examples, see the entry [Task.Run vs. Task.Factory.StartNew](https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/) in the Parallel Programming with .NET blog. + ]]> The provided has already been disposed. - is . - - -or- - + is . + + -or- + is . specifies an invalid value. For more information, see the Remarks for @@ -5740,6 +5765,7 @@ The NotOn\* and OnlyOn\* , Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Threading.Tasks/TaskFactory`1.xml b/xml/System.Threading.Tasks/TaskFactory`1.xml index af9120993a4..0f99ca7b213 100644 --- a/xml/System.Threading.Tasks/TaskFactory`1.xml +++ b/xml/System.Threading.Tasks/TaskFactory`1.xml @@ -52,40 +52,40 @@ The return value of the objects that the methods of this class create. Provides support for creating and scheduling objects. - class, which creates and objects. - -- The class, which creates objects. - - The class allows you to do the following: - -- Create a task and start it immediately by calling the method. You can call the overloads of this method to create and execute a task that requires non-default arguments. - + class, which creates and objects. + +- The class, which creates objects. + + The class allows you to do the following: + +- Create a task and start it immediately by calling the method. You can call the overloads of this method to create and execute a task that requires non-default arguments. + > [!WARNING] - > Starting with .NET Framework 4.5, the method provides the easiest way to create a task with default configuration values and start it immediately. - -- Create a task that starts when any one of the tasks in an array has completed by calling the or method. - -- Create a task that starts when all the tasks in an array have completed by calling the or method. - - The static property returns a default object. You can also call one of the class constructors to configure the objects that the class creates. The following example configures a new object to create tasks that have a specified cancellation token, task creation options, continuation options, and a customized task scheduler. - + > Starting with .NET Framework 4.5, the method provides the easiest way to create a task with default configuration values and start it immediately. + +- Create a task that starts when any one of the tasks in an array has completed by calling the or method. + +- Create a task that starts when all the tasks in an array have completed by calling the or method. + + The static property returns a default object. You can also call one of the class constructors to configure the objects that the class creates. The following example configures a new object to create tasks that have a specified cancellation token, task creation options, continuation options, and a customized task scheduler. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskFactory`1/Overview/factoriestresult.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/tpl_factories/vb/factoriestresult.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/tpl_factories/vb/factoriestresult.vb" id="Snippet2"::: + In most cases, you do not have to instantiate a new instance. Instead, you can use the static property, which returns a factory object that uses default values. You can then call its methods to start new tasks or define task continuations. For an illustration, see the example. - -## Examples - The following example uses the static property to make two calls to the method. The first task returns a string array that is populated with the names of files in the user's MyDocuments directory, while the second returns a string array that is populated with the names of subdirectories of the user's MyDocuments directory. It then calls the method, which displays information about the number of files and directories in the arrays returned by the two tasks after they have completed execution. - + +## Examples + The following example uses the static property to make two calls to the method. The first task returns a string array that is populated with the names of files in the user's MyDocuments directory, while the second returns a string array that is populated with the names of subdirectories of the user's MyDocuments directory. It then calls the method, which displays information about the number of files and directories in the arrays returned by the two tasks after they have completed execution. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Factory/factory2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.factory/vb/factory2.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.factory/vb/factory2.vb" id="Snippet2"::: + ]]> All public and protected members of are thread-safe and may be used concurrently from multiple threads. @@ -138,11 +138,11 @@ Initializes a instance with the default configuration. - instance with a default configuration. The property is initialized to , the property is initialized to , and the property is initialized to the current scheduler (see ). - + instance with a default configuration. The property is initialized to , the property is initialized to , and the property is initialized to the current scheduler (see ). + ]]> Task Parallel Library (TPL) @@ -187,14 +187,15 @@ The default cancellation token that will be assigned to tasks created by this unless another cancellation token is explicitly specified when calling the factory methods. Initializes a instance with the default configuration. - instance with a default configuration. The property is initialized to , the property is initialized to , and the property is initialized to the current scheduler (see ). - + instance with a default configuration. The property is initialized to , the property is initialized to , and the property is initialized to the current scheduler (see ). + ]]> Task Parallel Library (TPL) + The cancellation token was canceled. This exception is stored into the returned task. @@ -237,11 +238,11 @@ The scheduler to use to schedule any tasks created with this . A null value indicates that the current should be used. Initializes a instance with the specified configuration. - property is initialized to , the property is initialized to , and the property is initialized to `scheduler`, unless it's `null`, in which case the property is initialized to the current scheduler (see ). - + property is initialized to , the property is initialized to , and the property is initialized to `scheduler`, unless it's `null`, in which case the property is initialized to the current scheduler (see ). + ]]> @@ -291,11 +292,11 @@ The default options to use when creating continuation tasks with this . Initializes a instance with the specified configuration. - property is initialized to `creationOptions`, the property is initialized to `continuationOptions`, and the property is initialized to the current scheduler (see ). - + property is initialized to `creationOptions`, the property is initialized to `continuationOptions`, and the property is initialized to the current scheduler (see ). + ]]> @@ -351,11 +352,11 @@ The default scheduler to use to schedule any tasks created with this . A null value indicates that should be used. Initializes a instance with the specified configuration. - property is initialized to `creationOptions`, the property is initialized to `continuationOptions`, and the property is initialized to `scheduler`, unless it's `null`, in which case the property is initialized to the current scheduler (see ). - + property is initialized to `creationOptions`, the property is initialized to `continuationOptions`, and the property is initialized to `scheduler`, unless it's `null`, in which case the property is initialized to the current scheduler (see ). + ]]> @@ -363,6 +364,7 @@ Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -404,11 +406,11 @@ Gets the default cancellation token for this task factory. The default cancellation token for this task factory. - Task Parallel Library (TPL) @@ -454,11 +456,11 @@ Gets the enumeration value for this task factory. One of the enumeration values that specifies the default continuation options for this task factory. - Task Parallel Library (TPL) @@ -523,19 +525,19 @@ Creates a continuation task that will be started upon the completion of a set of provided tasks. The new continuation task. - , , or states. - + , , or states. + ]]> One of the elements in the array has been disposed. - array is . - - -or- - + array is . + + -or- + The is . The array contains a null value or is empty. Task Parallel Library (TPL) @@ -590,27 +592,28 @@ Creates a continuation task that will be started upon the completion of a set of provided tasks. The new continuation task. - , , or states. - + , , or states. + ]]> - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The that created has already been disposed. - The array is . - - -or- - + The array is . + + -or- + is . The array contains a null value or is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -660,18 +663,18 @@ Creates a continuation task that will be started upon the completion of a set of provided Tasks. The new continuation task. - , , or states. - + , , or states. + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The argument specifies an invalid value. The array contains a null value or is empty. @@ -731,33 +734,34 @@ Creates a continuation task that will be started upon the completion of a set of provided Tasks. The new continuation task. - , , or states. - + , , or states. + ]]> - The array is . - - -or- - - The argument is . - - -or- - + The array is . + + -or- + + The argument is . + + -or- + The argument is . The array contains a null value or is empty. specifies an invalid value. - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The that created has already been disposed. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -809,18 +813,18 @@ Creates a continuation task that will be started upon the completion of a set of provided tasks. The new continuation task. - , , or states. - + , , or states. + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array contains a null value or is empty. Task Parallel Library (TPL) @@ -879,27 +883,28 @@ Creates a continuation task that will be started upon the completion of a set of provided tasks. The new continuation task. - , , or states. - + , , or states. + ]]> - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The that created has already been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array contains a null value or is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -953,18 +958,18 @@ Creates a continuation task that will be started upon the completion of a set of provided tasks. The new continuation task. - , , or states. - + , , or states. + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The argument specifies an invalid value. The array contains a null value or is empty. @@ -1028,32 +1033,33 @@ Creates a continuation task that will be started upon the completion of a set of provided tasks. The new continuation task. - , , or states. - + , , or states. + ]]> - The array is . - - -or- - - The argument is . - - -or- - + The array is . + + -or- + + The argument is . + + -or- + The argument is . The array contains a null value or is empty. The argument specifies an invalid value. - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The that created has already been disposed. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1114,18 +1120,18 @@ Creates a continuation task that will be started upon the completion of any task in the provided set. The new continuation task. - , , or states. - + , , or states. + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The array contains a null value or is empty. Task Parallel Library (TPL) @@ -1180,31 +1186,32 @@ Creates a continuation task that will be started upon the completion of any task in the provided set. The new continuation task. - , , or states. - + , , or states. + ]]> - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The that created has already been disposed. - The array is null. - - -or- - + The array is null. + + -or- + The argument is null. - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1254,24 +1261,24 @@ Creates a continuation task that will be started upon the completion of any task in the provided set. The new continuation task. - , , or states. - + , , or states. + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The argument specifies an invalid enumeration value. - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -1329,37 +1336,38 @@ Creates a continuation task that will be started upon the completion of any task in the provided set. The new continuation task. - , , or states. - + , , or states. + ]]> - The array is . - - -or- - - The argument is . - - -or- - + The array is . + + -or- + + The argument is . + + -or- + The argument is . - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. The argument specifies an invalid value. - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The that created has already been disposed. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1411,23 +1419,23 @@ Creates a continuation task that will be started upon the completion of any task in the provided set. The new continuation . - , , or states. - + , , or states. + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -1485,31 +1493,32 @@ Creates a continuation task that will be started upon the completion of any task in the provided set. The new continuation task. - , , or states. - + , , or states. + ]]> - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The that created has already been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1563,24 +1572,24 @@ Creates a continuation task that will be started upon the completion of any task in the provided set. The new continuation . - , , or states. - + , , or states. + ]]> One of the elements in the array has been disposed. - The array is . - - -or- - + The array is . + + -or- + The argument is . The argument specifies an invalid enumeration value. - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks @@ -1642,36 +1651,37 @@ Creates a continuation task that will be started upon the completion of any task in the provided set. The new continuation . - , , or states. - + , , or states. + ]]> - The array is . - - -or- - - The argument is . - - -or- - + The array is . + + -or- + + The argument is . + + -or- + The argument is null. - The array contains a null value. - - -or- - + The array contains a null value. + + -or- + The array is empty. The argument specifies an invalid TaskContinuationOptions value. - One of the elements in the array has been disposed. - - -or- - + One of the elements in the array has been disposed. + + -or- + The that created has already been disposed. Task Parallel Library (TPL) Chaining Tasks by Using Continuation Tasks Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -1713,11 +1723,11 @@ Gets the enumeration value for this task factory. One of the enumeration values that specifies the default creation options for this task factory. - Task Parallel Library (TPL) @@ -1781,10 +1791,10 @@ Creates a task that executes an end method function when a specified completes. A that represents the asynchronous operation. To be added. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -1838,17 +1848,17 @@ Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created task that represents the asynchronous operation. - - The argument is . - - -or- - + The argument is . + + -or- + The argument is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -1901,10 +1911,10 @@ Creates a task that executes an end method function when a specified completes. A task that represents the asynchronous operation. To be added. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The argument specifies an invalid value. Task Parallel Library (TPL) @@ -1961,17 +1971,17 @@ Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created that represents the asynchronous operation. - - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The argument specifies an invalid value. Task Parallel Library (TPL) @@ -2027,14 +2037,14 @@ Creates a task that executes an end method function when a specified completes. The created task that represents the asynchronous operation. To be added. - The argument is . - - -or- - - The argument is . - - -or- - + The argument is . + + -or- + + The argument is . + + -or- + The argument is . The parameter specifies an invalid value. Task Parallel Library (TPL) @@ -2095,17 +2105,17 @@ Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created task that represents the asynchronous operation. - - The argument is . - - -or- - + The argument is . + + -or- + The argument is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -2167,17 +2177,17 @@ Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created task that represents the asynchronous operation. - - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The parameter specifies an invalid value. Task Parallel Library (TPL) @@ -2242,17 +2252,17 @@ Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created task that represents the asynchronous operation. - - The argument is . - - -or- - + The argument is . + + -or- + The argument is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -2318,17 +2328,17 @@ Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created task that represents the asynchronous operation. - - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The parameter specifies an invalid value. Task Parallel Library (TPL) @@ -2397,17 +2407,17 @@ Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created task that represents the asynchronous operation. - - The argument is . - - -or- - + The argument is . + + -or- + The argument is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns @@ -2477,17 +2487,17 @@ Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern. The created task that represents the asynchronous operation. - - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The parameter specifies an invalid value. Task Parallel Library (TPL) @@ -2534,13 +2544,13 @@ Gets the task scheduler for this task factory. The task scheduler for this task factory. - will be used. - + will be used. + ]]> Task Parallel Library (TPL) @@ -2602,13 +2612,13 @@ Creates and starts a task. The started task. - constructors, and then calling the method to schedule it for execution. - - However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. - + constructors, and then calling the method to schedule it for execution. + + However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. + ]]> The argument is . @@ -2662,13 +2672,13 @@ Creates and starts a task. The started task. - constructors and then calling the method to schedule it for execution. - - However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. - + constructors and then calling the method to schedule it for execution. + + However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. + ]]> The argument is . @@ -2721,19 +2731,20 @@ Creates and starts a task. The started task. - constructors and then calling the method to schedule it for execution. - - However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. - + constructors and then calling the method to schedule it for execution. + + However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. + ]]> The cancellation token source that created has already been disposed. The argument is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns + The cancellation token was canceled. This exception is stored into the returned task. @@ -2781,13 +2792,13 @@ Creates and starts a task. The started . - constructors and then calling the method to schedule it for execution. - - However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. - + constructors and then calling the method to schedule it for execution. + + However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. + ]]> The argument is . @@ -2844,19 +2855,20 @@ Creates and starts a task. The started task. - constructors and then calling the method to schedule it for execution. - - However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. - + constructors and then calling the method to schedule it for execution. + + However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. + ]]> The cancellation token source that created has already been disposed. The argument is . Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns + The cancellation token was canceled. This exception is stored into the returned task. @@ -2907,13 +2919,13 @@ Creates and starts a task. The started task. - constructors and then calling the method to schedule it for execution. - - However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. - + constructors and then calling the method to schedule it for execution. + + However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. + ]]> The argument is . @@ -2971,24 +2983,25 @@ Creates and starts a task. The started task. - constructors and then calling the method to schedule it for execution. - - However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. - + constructors and then calling the method to schedule it for execution. + + However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. + ]]> The cancellation token source that created has already been disposed. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The parameter specifies an invalid value. Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns + The cancellation token was canceled. This exception is stored into the returned task. @@ -3043,24 +3056,25 @@ Creates and starts a task. The started task. - constructors and then calling the method to schedule it for execution. - - However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. - + constructors and then calling the method to schedule it for execution. + + However, unless creation and scheduling must be separated, `StartNew` is the recommended approach for both simplicity and performance. + ]]> The cancellation token source that created has already been disposed. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The parameter specifies an invalid value. Task Parallel Library (TPL) Using TPL with Other Asynchronous Patterns + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Threading.Tasks/Task`1.xml b/xml/System.Threading.Tasks/Task`1.xml index d4ba051196d..3cf344fad94 100644 --- a/xml/System.Threading.Tasks/Task`1.xml +++ b/xml/System.Threading.Tasks/Task`1.xml @@ -62,29 +62,29 @@ The type of the result produced by this . Represents an asynchronous operation that can return a value. - class represents a single operation that returns a value and that usually executes asynchronously. objects are one of the central components of the [task-based asynchronous pattern](/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap) first introduced in the .NET Framework 4. Because the work performed by a object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the property, as well as the , , and properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform. - - instances may be created in a variety of ways. The most common approach, which is available starting with the .NET Framework 4.5, is to call the static or method. These methods provide a simple way to start a task by using default values and without acquiring additional parameters. The following example uses the method to start a task that loops and then displays the number of loop iterations: - + class represents a single operation that returns a value and that usually executes asynchronously. objects are one of the central components of the [task-based asynchronous pattern](/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap) first introduced in the .NET Framework 4. Because the work performed by a object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the property, as well as the , , and properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform. + + instances may be created in a variety of ways. The most common approach, which is available starting with the .NET Framework 4.5, is to call the static or method. These methods provide a simple way to start a task by using default values and without acquiring additional parameters. The following example uses the method to start a task that loops and then displays the number of loop iterations: + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskTResult/Overview/run1.cs" id="Snippet6"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1/vb/run1.vb" id="Snippet6"::: - - An alternative, and the most common way to start a task in the .NET Framework 4, is to call the static or method. The property returns a object, and the property returns a object. Overloads of their `StartNew` method let you pass arguments, define task creation options, and specify a task scheduler. The following example uses the method to start a task. It is functionally equivalent to the code in the previous example. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1/vb/run1.vb" id="Snippet6"::: + + An alternative, and the most common way to start a task in the .NET Framework 4, is to call the static or method. The property returns a object, and the property returns a object. Overloads of their `StartNew` method let you pass arguments, define task creation options, and specify a task scheduler. The following example uses the method to start a task. It is functionally equivalent to the code in the previous example. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskTResult/Overview/startnew1.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1/vb/startnew1.vb" id="Snippet7"::: - - For more complete examples, see [Task-based Asynchronous Programming](/dotnet/standard/parallel-programming/task-based-asynchronous-programming). - - The class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the and `Task.Factory.StartNew` methods are the preferred mechanisms for creating and scheduling computational tasks, but for scenarios where task creation and scheduling must be separated, the constructors may be used, and the task's method may then be used to schedule the task for execution at a later time. - - Starting with desktop apps that target the .NET Framework 4.6, the culture of the thread that creates and invokes a task becomes part of the thread's context. That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. For apps that target versions of the .NET Framework prior to the .NET Framework 4.6, the culture of the task is the culture of the thread on which the task executes. For more information, see the "Culture and task-based asynchronous operations" section in the topic. Note that Store apps follow the Windows Runtime in setting and getting the default culture. - -For operations that do not return a value, you use the class. Starting with C# 7.0, for a more lightweight task that is a value type rather than a reference type, use the structure. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1/vb/startnew1.vb" id="Snippet7"::: + + For more complete examples, see [Task-based Asynchronous Programming](/dotnet/standard/parallel-programming/task-based-asynchronous-programming). + + The class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the and `Task.Factory.StartNew` methods are the preferred mechanisms for creating and scheduling computational tasks, but for scenarios where task creation and scheduling must be separated, the constructors may be used, and the task's method may then be used to schedule the task for execution at a later time. + + Starting with desktop apps that target the .NET Framework 4.6, the culture of the thread that creates and invokes a task becomes part of the thread's context. That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. For apps that target versions of the .NET Framework prior to the .NET Framework 4.6, the culture of the task is the culture of the thread on which the task executes. For more information, see the "Culture and task-based asynchronous operations" section in the topic. Note that Store apps follow the Windows Runtime in setting and getting the default culture. + +For operations that do not return a value, you use the class. Starting with C# 7.0, for a more lightweight task that is a value type rather than a reference type, use the structure. + ]]> All members of , except for , are thread-safe and may be used from multiple threads concurrently. @@ -143,27 +143,27 @@ For operations that do not return a value, you use the The delegate that represents the code to execute in the task. When the function has completed, the task's property will be set to return the result value of the function. Initializes a new with the specified function. - object and launch a task is by calling the static and methods. - - If a task with no action is needed just for the consumer of an API to have something to await, a should be used. - - - -## Examples - The following example counts the approximate number of words in text files that represent published books. Each task is responsible for opening a file, reading its entire contents asynchronously, and calculating the word count by using a regular expression. The method is called to ensure that all tasks have completed before displaying the word count of each book to the console. - - Object instantiation is separated from object execution in this example so that the example can ensure that each file exists. If they do not, it displays the name of the missing file. Otherwise, it calls the method to launch each task. - + object and launch a task is by calling the static and methods. + + If a task with no action is needed just for the consumer of an API to have something to await, a should be used. + + + +## Examples + The following example counts the approximate number of words in text files that represent published books. Each task is responsible for opening a file, reading its entire contents asynchronously, and calculating the word count by using a regular expression. The method is called to ensure that all tasks have completed before displaying the word count of each book to the console. + + Object instantiation is separated from object execution in this example so that the example can ensure that each file exists. If they do not, it displays the name of the missing file. Otherwise, it calls the method to launch each task. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run3.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/run3.vb" id="Snippet2"::: - - The regular expression pattern `\p{P}*\s+` matches zero, one, or more punctuation characters followed by one or more white-space characters. It assumes that the total number of matches equals the approximate word count. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/run3.vb" id="Snippet2"::: + + The regular expression pattern `\p{P}*\s+` matches zero, one, or more punctuation characters followed by one or more white-space characters. It assumes that the total number of matches equals the approximate word count. + ]]> The argument is . @@ -214,11 +214,11 @@ For operations that do not return a value, you use the An object representing data to be used by the action. Initializes a new with the specified function and state. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The argument is . @@ -268,11 +268,11 @@ For operations that do not return a value, you use the The to be assigned to this task. Initializes a new with the specified function. - object and launch a task is by calling the static and methods. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static and methods. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The that created has already been disposed. @@ -280,6 +280,7 @@ For operations that do not return a value, you use the Task Parallel Library (TPL) Task-based Asynchronous Programming The argument is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -323,11 +324,11 @@ For operations that do not return a value, you use the The used to customize the task's behavior. Initializes a new with the specified function and creation options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The argument specifies an invalid value for . @@ -381,11 +382,11 @@ For operations that do not return a value, you use the The to be assigned to the new task. Initializes a new with the specified action, state, and options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The that created has already been disposed. @@ -393,6 +394,7 @@ For operations that do not return a value, you use the Task Parallel Library (TPL) Task-based Asynchronous Programming The argument is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -439,11 +441,11 @@ For operations that do not return a value, you use the The used to customize the task's behavior. Initializes a new with the specified action, state, and options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The argument specifies an invalid value for . @@ -496,11 +498,11 @@ For operations that do not return a value, you use the The used to customize the task's behavior. Initializes a new with the specified function and creation options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The that created has already been disposed. @@ -509,6 +511,7 @@ For operations that do not return a value, you use the Task Parallel Library (TPL) Task-based Asynchronous Programming The argument is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -557,11 +560,11 @@ For operations that do not return a value, you use the The used to customize the task's behavior. Initializes a new with the specified action, state, and options. - object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. - + object and launch a task is by calling the static method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation. + ]]> The that created has already been disposed. @@ -570,6 +573,7 @@ For operations that do not return a value, you use the Task Parallel Library (TPL) Task-based Asynchronous Programming The argument is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -679,19 +683,19 @@ For operations that do not return a value, you use the Creates a continuation that executes asynchronously when the target task completes. A new continuation task. - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting early due to being canceled. - - - -## Examples - The following example creates an antecedent task that uses the Sieve of Eratosthenes to calculate the prime numbers between 1 and a value entered by the user. An array is used to hold information about the prime numbers. The array index represents the number, and the element's value indicates whether that number is composite (its value is `true`) or prime (its value is `false`). This task is then passed to a continuation task, which is responsible for extracting the prime numbers from the integer array and displaying them. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting early due to being canceled. + + + +## Examples + The following example creates an antecedent task that uses the Sieve of Eratosthenes to calculate the prime numbers between 1 and a value entered by the user. An array is used to hold information about the prime numbers. The array index represents the number, and the element's value indicates whether that number is composite (its value is `true`) or prime (its value is `false`). This task is then passed to a continuation task, which is responsible for extracting the prime numbers from the integer array and displaying them. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskTResult/ContinueWith/continue2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1.continuewith/vb/continue2.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1.continuewith/vb/continue2.vb" id="Snippet2"::: + ]]> The has been disposed. @@ -747,19 +751,19 @@ For operations that do not return a value, you use the Creates a continuation that is passed state information and that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - - - -## Examples - The following example creates a task that is passed an integer between 2 and 20 and returns an array that contains the first ten exponents (from n1 to n10) of that number. A continuation task is then responsible for displaying the exponents. It is passed both the antecedent and the original number whose exponents the antecedent generates. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + + + +## Examples + The following example creates a task that is passed an integer between 2 and 20 and returns an array that contains the first ten exponents (from n1 to n10) of that number. A continuation task is then responsible for displaying the exponents. It is passed both the antecedent and the original number whose exponents the antecedent generates. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskTResult/ContinueWith/continuewith3.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1.continuewith/vb/continuewith3.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1.continuewith/vb/continuewith3.vb" id="Snippet3"::: + ]]> The argument is . @@ -811,34 +815,35 @@ For operations that do not return a value, you use the Creates a cancelable continuation that executes asynchronously when the target completes. A new continuation task. - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - - - -## Examples - The following example creates an antecedent task that uses the Sieve of Eratosthenes to calculate the prime numbers between 1 and a value entered by the user. An array is used to hold information about the prime numbers. The array index represents the number, and the element's value indicates whether that number is composite (its value is `true`) or prime (its value is `false`). This task is then passed to a continuation task, which is responsible for extracting the prime numbers from the integer array and displaying them. - - A cancellation token is passed to both the antecedent and the continuation task. A object is used to define a timeout value of 100 milliseconds. If the event fires, the method is called, and the cancellation token is used to request cancellation of the tasks. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + + + +## Examples + The following example creates an antecedent task that uses the Sieve of Eratosthenes to calculate the prime numbers between 1 and a value entered by the user. An array is used to hold information about the prime numbers. The array index represents the number, and the element's value indicates whether that number is composite (its value is `true`) or prime (its value is `false`). This task is then passed to a continuation task, which is responsible for extracting the prime numbers from the integer array and displaying them. + + A cancellation token is passed to both the antecedent and the continuation task. A object is used to define a timeout value of 100 milliseconds. If the event fires, the method is called, and the cancellation token is used to request cancellation of the tasks. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/TaskTResult/ContinueWith/continue1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1.continuewith/vb/continue1.vb" id="Snippet1"::: - - Typically, supplying a value of about 100,000 causes the timeout interval to expire and the event to fire, and the cancellation request to be set. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task`1.continuewith/vb/continue1.vb" id="Snippet1"::: + + Typically, supplying a value of about 100,000 causes the timeout interval to expire and the event to fire, and the cancellation request to be set. + ]]> - The has been disposed. - - -or- - + The has been disposed. + + -or- + The that created has been disposed. The argument is . Task Parallel Library (TPL) Task-based Asynchronous Programming Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -886,13 +891,13 @@ For operations that do not return a value, you use the Creates a continuation that executes according the condition specified in . A new continuation . - will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - - For more information, see [Chaining Tasks by Using Continuation Tasks](/dotnet/standard/parallel-programming/chaining-tasks-by-using-continuation-tasks). - + will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + + For more information, see [Chaining Tasks by Using Continuation Tasks](/dotnet/standard/parallel-programming/chaining-tasks-by-using-continuation-tasks). + ]]> The has been disposed. @@ -948,18 +953,18 @@ For operations that do not return a value, you use the Creates a continuation that executes asynchronously when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The has been disposed. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . Task Parallel Library (TPL) Task-based Asynchronous Programming @@ -1014,16 +1019,17 @@ For operations that do not return a value, you use the Creates a continuation that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The argument is . The provided has already been disposed. Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -1074,11 +1080,11 @@ For operations that do not return a value, you use the Creates a continuation that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - + will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + ]]> The argument is . @@ -1134,11 +1140,11 @@ For operations that do not return a value, you use the Creates a continuation that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The argument is . @@ -1194,27 +1200,28 @@ For operations that do not return a value, you use the Creates a continuation that executes according the condition specified in . A new continuation . - will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. For more information, see [Chaining Tasks by Using Continuation Tasks](/dotnet/standard/parallel-programming/chaining-tasks-by-using-continuation-tasks). - + will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. For more information, see [Chaining Tasks by Using Continuation Tasks](/dotnet/standard/parallel-programming/chaining-tasks-by-using-continuation-tasks). + ]]> - The has been disposed. - - -or- - + The has been disposed. + + -or- + The that created has already been disposed. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The argument specifies an invalid value for . Task Parallel Library (TPL) Task-based Asynchronous Programming Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -1269,17 +1276,18 @@ For operations that do not return a value, you use the Creates a continuation that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. - + will not be scheduled for execution until the current task has completed. If the criteria specified through the `continuationOptions` parameter are not met, the continuation task will be canceled instead of scheduled. + ]]> The argument is . The argument specifies an invalid value for . The provided has already been disposed. Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -1329,11 +1337,11 @@ For operations that do not return a value, you use the Creates a continuation that executes asynchronously when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The has been disposed. @@ -1393,19 +1401,19 @@ For operations that do not return a value, you use the Creates a continuation that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - - - -## Examples - The following example creates a chain of continuation tasks. Each task provides the current time, a object, for the state argument of the method. Each value represents the time at which the continue task is created. Each task produces as its result a second value that represents the time at which the task finishes. After all tasks finish, the example displays the date and times at which each continuation task starts and finishes. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + + + +## Examples + The following example creates a chain of continuation tasks. Each task provides the current time, a object, for the state argument of the method. Each value represents the time at which the continue task is created. Each task produces as its result a second value that represents the time at which the task finishes. After all tasks finish, the example displays the date and times at which each continuation task starts and finishes. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task`1/ContinueWith/continuationstate.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/tpl_continuationstate/vb/continuationstate.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/tpl_continuationstate/vb/continuationstate.vb" id="Snippet1"::: + ]]> The argument is . @@ -1461,22 +1469,23 @@ For operations that do not return a value, you use the Creates a continuation that executes asynchronously when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> - The has been disposed. - - -or- - + The has been disposed. + + -or- + The that created has already been disposed. The argument is . Task Parallel Library (TPL) Task-based Asynchronous Programming Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -1523,20 +1532,20 @@ For operations that do not return a value, you use the The type of the result produced by the continuation. - A function to run according the condition specified in . - + A function to run according the condition specified in . + When run, the delegate will be passed the completed task as an argument. Options for when the continuation is scheduled and how it behaves. This includes criteria, such as , as well as execution options, such as . Creates a continuation that executes according the condition specified in . A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - - The `continuationFunction`, when executed, should return a . - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + + The `continuationFunction`, when executed, should return a . + ]]> The has been disposed. @@ -1596,18 +1605,18 @@ For operations that do not return a value, you use the Creates a continuation that executes asynchronously when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The has been disposed. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . Task Parallel Library (TPL) @@ -1667,16 +1676,17 @@ For operations that do not return a value, you use the Creates a continuation that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The argument is . The provided has already been disposed. Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -1731,13 +1741,13 @@ For operations that do not return a value, you use the Creates a continuation that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - - The `continuationFunction`, when executed, should return a . This task's completion state will be transferred to the task returned from the ContinueWith call. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + + The `continuationFunction`, when executed, should return a . This task's completion state will be transferred to the task returned from the ContinueWith call. + ]]> The argument is . @@ -1797,11 +1807,11 @@ For operations that do not return a value, you use the Creates a continuation that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + ]]> The argument is . @@ -1854,8 +1864,8 @@ For operations that do not return a value, you use the The type of the result produced by the continuation. - A function to run according the condition specified in . - + A function to run according the condition specified in . + When run, the delegate will be passed as an argument this completed task. The that will be assigned to the new task. Options for when the continuation is scheduled and how it behaves. This includes criteria, such as , as well as execution options, such as . @@ -1863,29 +1873,30 @@ For operations that do not return a value, you use the Creates a continuation that executes according the condition specified in . A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - - The `continuationFunction`, when executed, should return a . - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + + The `continuationFunction`, when executed, should return a . + ]]> - The has been disposed. - - -or- - + The has been disposed. + + -or- + The that created has already been disposed. - The argument is . - - -or- - + The argument is . + + -or- + The argument is . The argument specifies an invalid value for . Task Parallel Library (TPL) Task-based Asynchronous Programming Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -1944,19 +1955,20 @@ For operations that do not return a value, you use the Creates a continuation that executes when the target completes. A new continuation . - will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. - - The `continuationFunction`, when executed, should return a . This task's completion state will be transferred to the task returned from the call. - + will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled. + + The `continuationFunction`, when executed, should return a . This task's completion state will be transferred to the task returned from the call. + ]]> The argument is . The argument specifies an invalid value for . The provided has already been disposed. Chaining Tasks by Using Continuation Tasks + The cancellation token was canceled. This exception is stored into the returned task. @@ -1998,28 +2010,28 @@ For operations that do not return a value, you use the Gets a factory method for creating and configuring instances. A factory object that can create a variety of objects. - class that is identical to the one created by calling the parameterless constructor. It has the following property values: - -|Property|Value| -|--------------|-----------| -||| -||| -||| -||`null`, or | - - The most common use of this property is to create and start a new task in a single call to the method. - + class that is identical to the one created by calling the parameterless constructor. It has the following property values: + +|Property|Value| +|--------------|-----------| +||| +||| +||| +||`null`, or | + + The most common use of this property is to create and start a new task in a single call to the method. + > [!NOTE] -> Starting with the .NET Framework 4.5, the method provides the easiest way to create a object with default configuration values. - - The following example uses the static property to make three calls to the method. The first starts a `Task` object, which executes a lambda expression that returns 1. The second starts a `Task` object, which executes a lambda expression that instantiates a new `Test` instance. The third starts a `Task` object, which enumerates the files in the C:\Users\Public\Pictures\Sample Pictures\ directory. (Note that successful execution of the example requires that the directory exist and that it contain files. - +> Starting with the .NET Framework 4.5, the method provides the easiest way to create a object with default configuration values. + + The following example uses the static property to make three calls to the method. The first starts a `Task` object, which executes a lambda expression that returns 1. The second starts a `Task` object, which executes a lambda expression that instantiates a new `Test` instance. The third starts a `Task` object, which enumerates the files in the C:\Users\Public\Pictures\Sample Pictures\ directory. (Note that successful execution of the example requires that the directory exist and that it contain files. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task`1/Factory/returnavalue10.cs" id="Snippet10"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/tpl/vb/10_returnavalue.vb" id="Snippet10"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Misc/tpl/vb/10_returnavalue.vb" id="Snippet10"::: + ]]> Task Parallel Library (TPL) @@ -2131,27 +2143,27 @@ This method is intended for compiler use rather than use directly in code. Gets the result value of this . The result value of this , which is of the same type as the task's type parameter. - method. - - Once the result of an operation is available, it is stored and is returned immediately on subsequent calls to the property. Note that, if an exception occurred during the operation of the task, or if the task has been cancelled, the property does not return a value. Instead, attempting to access the property value throws an exception. - - - -## Examples - The following example is a command-line utility that calculates the number of bytes in the files in each directory whose name is passed as a command-line argument. If the directory contains files, it executes a lambda expression that instantiates a object for each file in the directory and retrieves the value of its property. If a directory contains no files, it simply calls the method to create a task whose property is zero (0). When the tasks finish, the total number of bytes in all a directory's files is available from the property. - + method. + + Once the result of an operation is available, it is stored and is returned immediately on subsequent calls to the property. Note that, if an exception occurred during the operation of the task, or if the task has been cancelled, the property does not return a value. Instead, attempting to access the property value throws an exception. + + + +## Examples + The following example is a command-line utility that calculates the number of bytes in the files in each directory whose name is passed as a command-line argument. If the directory contains files, it executes a lambda expression that instantiates a object for each file in the directory and retrieves the value of its property. If a directory contains no files, it simply calls the method to create a task whose property is zero (0). When the tasks finish, the total number of bytes in all a directory's files is available from the property. + :::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.fromresult/vb/fromresult1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.fromresult/vb/fromresult1.vb" id="Snippet1"::: + ]]> - The task was canceled. The collection contains a object. - - -or- - + The task was canceled. The collection contains a object. + + -or- + An exception was thrown during the execution of the task. The collection contains information about the exception or exceptions. Task Parallel Library (TPL) Task-based Asynchronous Programming @@ -2191,6 +2203,7 @@ This method is intended for compiler use rather than use directly in code. Gets a that will complete when this completes or when the specified has cancellation requested. The representing the asynchronous wait. It may or may not be the same instance as the current instance. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2263,6 +2276,7 @@ This method is intended for compiler use rather than use directly in code. Gets a that will complete when this completes, when the specified timeout expires, or when the specified has cancellation requested. The representing the asynchronous wait. It may or may not be the same instance as the current instance. To be added. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Threading.Tasks/ValueTask.xml b/xml/System.Threading.Tasks/ValueTask.xml index 17b87cf1fdd..728c124c1d8 100644 --- a/xml/System.Threading.Tasks/ValueTask.xml +++ b/xml/System.Threading.Tasks/ValueTask.xml @@ -51,9 +51,9 @@ Provides an awaitable result of an asynchronous operation. - using . A `ValueTask` instance may only be awaited once, and consumers may not call until the instance has completed. If these limitations are unacceptable, convert the `ValueTask` to a by calling . The following operations should never be performed on a `ValueTask` instance: @@ -290,9 +290,9 @@ This method either returns the wrapped task object, if one exists, or it manufac if the specified object is equal to the current object; otherwise, . - instances are equal when they wrap the same or the same pair of the object and the token. ]]> @@ -337,9 +337,9 @@ Two instances are equal when they wrap t if the specified object is equal to the current object; otherwise, . - instances are equal when they wrap the same or the same pair of the object and the token. ]]> @@ -377,6 +377,7 @@ Two instances are equal when they wrap t Creates a that has completed due to cancellation with the specified cancellation token. The canceled task. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -414,6 +415,7 @@ Two instances are equal when they wrap t Creates a that has completed due to cancellation with the specified cancellation token. The canceled task. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -762,9 +764,9 @@ If the is backed by a result or by a if the two values are equal; otherwise, . - instances are equal when they wrap the same or the same pair of the object and the token. ]]> @@ -808,9 +810,9 @@ Two instances are equal when they wrap t if the two values are not equal; otherwise, . - instances are equal when they wrap the same or the same pair of the object and the token. ]]> @@ -848,7 +850,7 @@ Two instances are equal when they wrap t Gets a that may be used at any point in the future. The preserved . - can be backed by a pooled , it is not safe to await an arbitrary multiple times. You can use the method to convert this into the instance backed by a regular that is safe to await multiple times. This method is similar to , but it returns the same instance when this represents a successful synchronously completed operation. After calling the original should never be used again. diff --git a/xml/System.Threading/CancellationToken.xml b/xml/System.Threading/CancellationToken.xml index 183baf56f8e..a393faa866e 100644 --- a/xml/System.Threading/CancellationToken.xml +++ b/xml/System.Threading/CancellationToken.xml @@ -71,23 +71,23 @@ Propagates notification that operations should be canceled. - enables cooperative cancellation between threads, thread pool work items, or objects. You create a cancellation token by instantiating a object, which manages cancellation tokens retrieved from its property. You then pass the cancellation token to any number of threads, tasks, or operations that should receive notice of cancellation. The token cannot be used to initiate cancellation. When the owning object calls , the property on every copy of the cancellation token is set to `true`. The objects that receive the notification can respond in whatever manner is appropriate. - - For more information and code examples see [Cancellation in Managed Threads](/dotnet/standard/threading/cancellation-in-managed-threads). - - - -## Examples - The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed. - + enables cooperative cancellation between threads, thread pool work items, or objects. You create a cancellation token by instantiating a object, which manages cancellation tokens retrieved from its property. You then pass the cancellation token to any number of threads, tasks, or operations that should receive notice of cancellation. The token cannot be used to initiate cancellation. When the owning object calls , the property on every copy of the cancellation token is set to `true`. The objects that receive the notification can respond in whatever manner is appropriate. + + For more information and code examples see [Cancellation in Managed Threads](/dotnet/standard/threading/cancellation-in-managed-threads). + + + +## Examples + The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed. + To handle the possible cancellation of the operation, the example instantiates a object that generates a cancellation token that's passed to a object. In turn, the object passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. The method is called to ensure that the mean is computed only after all readings have been gathered successfully. If a task has not completed because it was cancelled, the method throws an exception. - + :::code language="csharp" source="~/snippets/csharp/System.Threading/CancellationToken/Overview/cancel1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.cancellationtokensource.class/vb/cancel1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.cancellationtokensource.class/vb/cancel1.vb" id="Snippet1"::: + ]]> All public and protected members of are thread-safe and may be used concurrently from multiple threads. @@ -134,13 +134,13 @@ To handle the possible cancellation of the operation, the example instantiates a The canceled state for the token. Initializes the . - and will be `false`. - - If `canceled` is `true`, both and will be `true`. - + and will be `false`. + + If `canceled` is `true`, both and will be `true`. + ]]> Cancellation @@ -193,13 +193,13 @@ To handle the possible cancellation of the operation, the example instantiates a if this token is capable of being in the canceled state; otherwise, . - returns `false`, it is guaranteed that the token will never transition into a canceled state, meaning that will never return `true`. A cancellation token that cannot be canceled is returned by the static property. - - You can optionally use this property to determine whether a cancellation token can be canceled before examining the value of the property to determine whether it has been canceled. - + returns `false`, it is guaranteed that the token will never transition into a canceled state, meaning that will never return `true`. A cancellation token that cannot be canceled is returned by the static property. + + You can optionally use this property to determine whether a cancellation token can be canceled before examining the value of the property to determine whether it has been canceled. + ]]> Cancellation @@ -268,10 +268,10 @@ To handle the possible cancellation of the operation, the example instantiates a if is a and if the two instances are equal; otherwise, . See the Remarks section for more information. - . @@ -335,10 +335,10 @@ Two cancellation tokens are equal if any one of the following conditions is true if the instances are equal; otherwise, . See the Remarks section for more information. - . @@ -350,6 +350,7 @@ Two cancellation tokens are equal if any one of the following conditions is true Cancellation Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -440,25 +441,25 @@ Two cancellation tokens are equal if any one of the following conditions is true if cancellation has been requested for this token; otherwise, . - on the token's associated . - - If this property is `true`, it only guarantees that cancellation has been requested. It does not guarantee that every registered handler has finished executing, nor that cancellation requests have finished propagating to all registered handlers. Additional synchronization may be required, particularly in situations where related objects are being canceled concurrently. - - - -## Examples - The following is a simple example that executes a server process until the property returns `true`. - + on the token's associated . + + If this property is `true`, it only guarantees that cancellation has been requested. It does not guarantee that every registered handler has finished executing, nor that cancellation requests have finished propagating to all registered handlers. Additional synchronization may be required, particularly in situations where related objects are being canceled concurrently. + + + +## Examples + The following is a simple example that executes a server process until the property returns `true`. + :::code language="csharp" source="~/snippets/csharp/System.Threading/CancellationToken/IsCancellationRequested/cancellation.cs" id="Snippet12"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/System.Threading.Tasks.CancellationToken.IsCancellationRequested/vb/cancelthreads.vb" id="Snippet12"::: - - The example instantiates a object, which controls access to the cancellation token. It then defines two thread procedures. The first is defined as a lambda expression that pools the keyboard and, when the "C" key is pressed, calls to set the cancellation token to the cancelled state. The second is a parameterized method, `ServerClass.StaticMethod`, that executes a loop until the property is `true`. - - The main thread then starts the two threads and blocks until the thread that executes the `ServerClass.StaticMethod` method terminates. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/System.Threading.Tasks.CancellationToken.IsCancellationRequested/vb/cancelthreads.vb" id="Snippet12"::: + + The example instantiates a object, which controls access to the cancellation token. It then defines two thread procedures. The first is defined as a lambda expression that pools the keyboard and, when the "C" key is pressed, calls to set the cancellation token to the cancelled state. The second is a parameterized method, `ServerClass.StaticMethod`, that executes a loop until the property is `true`. + + The main thread then starts the two threads and blocks until the thread that executes the `ServerClass.StaticMethod` method terminates. + ]]> Cancellation @@ -510,15 +511,15 @@ Two cancellation tokens are equal if any one of the following conditions is true Returns an empty value. An empty cancellation token. - property is `false`. - - You can also use the C# [default(CancellationToken)](/dotnet/csharp/language-reference/keywords/default) statement to create an empty cancellation token. + property is `false`. + + You can also use the C# [default(CancellationToken)](/dotnet/csharp/language-reference/keywords/default) statement to create an empty cancellation token. Two empty cancellation tokens are always equal. - + ]]> Cancellation @@ -571,10 +572,10 @@ Two cancellation tokens are equal if any one of the following conditions is true if the instances are equal; otherwise, See the Remarks section for more information. - . @@ -586,6 +587,7 @@ Two cancellation tokens are equal if any one of the following conditions is true An associated has been disposed. Cancellation Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -634,15 +636,16 @@ Two cancellation tokens are equal if any one of the following conditions is true if the instances are not equal; otherwise, . - method. +For the definition of equality, see the method. ]]> An associated has been disposed. Cancellation Task Cancellation + The cancellation token was canceled. This exception is stored into the returned task. @@ -700,15 +703,15 @@ For the definition of equality, see the Registers a delegate that will be called when this is canceled. The instance that can be used to unregister the callback. - is captured along with the delegate and will be used when executing it. + is captured along with the delegate and will be used when executing it. The current is not captured. - + ]]> The associated has been disposed. @@ -764,15 +767,15 @@ For the definition of equality, see the Registers a delegate that will be called when this is canceled. The instance that can be used to unregister the callback. - is captured along with the delegate and will be used when executing it. + is captured along with the delegate and will be used when executing it. If `useSynchronizationContext` is `true`, the current , if one exists, is also captured along with the delegate and will be used when executing it. Otherwise, is not captured. - + ]]> The associated has been disposed. @@ -878,15 +881,15 @@ is captured along with the delegate and is used when executing it. The current < Registers a delegate that will be called when this is canceled. The instance that can be used to unregister the callback. - is captured along with the delegate and will be used when executing it. + is captured along with the delegate and will be used when executing it. The current is not captured. - + ]]> The associated has been disposed. @@ -945,15 +948,15 @@ is captured along with the delegate and is used when executing it. The current < Registers a delegate that will be called when this is canceled. The instance that can be used to unregister the callback. - is captured along with the delegate and will be used when executing it. + is captured along with the delegate and will be used when executing it. If `useSynchronizationContext` is `true`, the current , if one exists, is also captured along with the delegate and will be used when executing it. Otherwise, is not captured. - + ]]> The associated has been disposed. @@ -1009,24 +1012,24 @@ is captured along with the delegate and is used when executing it. The current < Throws a if this token has had cancellation requested. - The token has had cancellation requested. @@ -1119,13 +1122,13 @@ generates is propagated out of this method call. The delegate to execute when the is canceled. The state to pass to the when the delegate is invoked. This may be . Registers a delegate that is called when this is canceled. - An object that can + An object that can be used to unregister the callback. is not captured or flowed to the callback's invocation. ]]> @@ -1173,11 +1176,11 @@ The is not captured or flowed Gets a that is signaled when the token is canceled. A that is signaled when the token is canceled. - to be instantiated. It is preferable to only use this property when necessary, and to then dispose the associated instance at the earliest opportunity (disposing the source will dispose of this allocated handle). The handle should not be closed or disposed directly. - + to be instantiated. It is preferable to only use this property when necessary, and to then dispose the associated instance at the earliest opportunity (disposing the source will dispose of this allocated handle). The handle should not be closed or disposed directly. + ]]> The associated has been disposed. diff --git a/xml/System.Threading/CancellationTokenSource.xml b/xml/System.Threading/CancellationTokenSource.xml index d05ecfdf478..19d08abebb2 100644 --- a/xml/System.Threading/CancellationTokenSource.xml +++ b/xml/System.Threading/CancellationTokenSource.xml @@ -59,42 +59,42 @@ Signals to a that it should be canceled. - object, which provides a cancellation token through its property and sends a cancellation message by calling its or method. - -- A object, which indicates whether cancellation is requested. - - The general pattern for implementing the cooperative cancellation model is: - -- Instantiate a object, which manages and sends cancellation notification to the individual cancellation tokens. - -- Pass the token returned by the property to each task or thread that listens for cancellation. - -- Call the method from operations that receive the cancellation token. Provide a mechanism for each task or thread to respond to a cancellation request. Whether you choose to cancel an operation, and exactly how you do it, depends on your application logic. - -- Call the method to provide notification of cancellation. This sets the property on every copy of the cancellation token to `true`. - -- Call the method when you are finished with the object. - - For more information, see [Cancellation in Managed Threads](/dotnet/standard/threading/cancellation-in-managed-threads). - + object, which provides a cancellation token through its property and sends a cancellation message by calling its or method. + +- A object, which indicates whether cancellation is requested. + + The general pattern for implementing the cooperative cancellation model is: + +- Instantiate a object, which manages and sends cancellation notification to the individual cancellation tokens. + +- Pass the token returned by the property to each task or thread that listens for cancellation. + +- Call the method from operations that receive the cancellation token. Provide a mechanism for each task or thread to respond to a cancellation request. Whether you choose to cancel an operation, and exactly how you do it, depends on your application logic. + +- Call the method to provide notification of cancellation. This sets the property on every copy of the cancellation token to `true`. + +- Call the method when you are finished with the object. + + For more information, see [Cancellation in Managed Threads](/dotnet/standard/threading/cancellation-in-managed-threads). + > [!IMPORTANT] -> This type implements the interface. When you have finished using an instance of the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`finally` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - - - -## Examples - The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed. - - To handle the possible cancellation of the operation, the example instantiates a object that generates a cancellation token which is passed to a object. The object in turn passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. The method is called to ensure that the mean is computed only after all readings have been gathered successfully. If a task has not completed because it has been cancelled, the call to the method throws an exception. - +> This type implements the interface. When you have finished using an instance of the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`finally` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. + + + +## Examples + The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed. + + To handle the possible cancellation of the operation, the example instantiates a object that generates a cancellation token which is passed to a object. The object in turn passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. The method is called to ensure that the mean is computed only after all readings have been gathered successfully. If a task has not completed because it has been cancelled, the call to the method throws an exception. + :::code language="csharp" source="~/snippets/csharp/System.Threading/CancellationToken/Overview/cancel1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.cancellationtokensource.class/vb/cancel1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.cancellationtokensource.class/vb/cancel1.vb" id="Snippet1"::: + ]]> All public and protected members of are thread-safe and may be used concurrently from multiple threads, with the exception of , which must only be used when all other operations on the object have completed. @@ -197,13 +197,13 @@ The time interval in milliseconds to wait before canceling this . Initializes a new instance of the class that will be canceled after the specified delay in milliseconds. - is canceled (if it has not been canceled already). - - Subsequent calls to will reset the `millisecondsDelay` for the constructed , if it has not been canceled already. - + is canceled (if it has not been canceled already). + + Subsequent calls to will reset the `millisecondsDelay` for the constructed , if it has not been canceled already. + ]]> @@ -249,13 +249,13 @@ The time interval to wait before canceling this . Initializes a new instance of the class that will be canceled after the specified time span. - is canceled, if it has not been canceled already. - - Subsequent calls to will reset the delay for the constructed , if it has not been canceled already. - + is canceled, if it has not been canceled already. + + Subsequent calls to will reset the delay for the constructed , if it has not been canceled already. + ]]> @@ -315,27 +315,27 @@ Communicates a request for cancellation. - will be notified of the cancellation and will transition to a state where returns true. - + will be notified of the cancellation and will transition to a state where returns true. + Any callbacks or cancelable operations registered with the will be executed. - + We recommend that cancelable operations and callbacks registered with not throw exceptions. - + This overload of Cancel will aggregate any exceptions thrown into an , such that one callback throwing an exception will not prevent other registered callbacks from being executed. Calling this method has the same effect as calling [`Cancel(false)`](xref:System.Threading.CancellationTokenSource.Cancel(System.Boolean)). -## Examples - The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed. - - To handle the possible cancellation of the operation, the example instantiates a object that generates a cancellation token which is passed to a object. The object in turn passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. The method is called to ensure that the mean is computed only after all readings have been gathered successfully. If a task has not because it has been cancelled, the call to the method throws an exception. - +## Examples + The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed. + + To handle the possible cancellation of the operation, the example instantiates a object that generates a cancellation token which is passed to a object. The object in turn passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. The method is called to ensure that the mean is computed only after all readings have been gathered successfully. If a task has not because it has been cancelled, the call to the method throws an exception. + :::code language="csharp" source="~/snippets/csharp/System.Threading/CancellationToken/Overview/cancel1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.cancellationtokensource.class/vb/cancel1.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.cancellationtokensource.class/vb/cancel1.vb" id="Snippet1"::: + ]]> This has been disposed. @@ -387,19 +387,19 @@ if exceptions should immediately propagate; otherwise, . Communicates a request for cancellation, and specifies whether remaining callbacks and cancelable operations should be processed if an exception occurs. - will be notified of the cancellation and will transition to a state where returns `true`. - - Any callbacks or cancelable operations registered with the will be executed. Callbacks will be executed synchronously in LIFO order. - - We recommend that cancelable operations and callbacks registered with not throw exceptions. - - If `throwOnFirstException` is `true`, an exception will immediately propagate out of the call to , preventing the remaining callbacks and cancelable operations from being processed. - - If `throwOnFirstException` is `false`, this overload will aggregate any exceptions thrown into an , such that one callback throwing an exception will not prevent other registered callbacks from being executed. - + will be notified of the cancellation and will transition to a state where returns `true`. + + Any callbacks or cancelable operations registered with the will be executed. Callbacks will be executed synchronously in LIFO order. + + We recommend that cancelable operations and callbacks registered with not throw exceptions. + + If `throwOnFirstException` is `true`, an exception will immediately propagate out of the call to , preventing the remaining callbacks and cancelable operations from being processed. + + If `throwOnFirstException` is `false`, this overload will aggregate any exceptions thrown into an , such that one callback throwing an exception will not prevent other registered callbacks from being executed. + ]]> This has been disposed. @@ -461,13 +461,13 @@ The time span to wait before canceling this . Schedules a cancel operation on this after the specified number of milliseconds. - is canceled, if it has not been canceled already. - - Subsequent calls to CancelAfter will reset the `millisecondsDelay` for this , if it has not been canceled already. - + is canceled, if it has not been canceled already. + + Subsequent calls to CancelAfter will reset the `millisecondsDelay` for this , if it has not been canceled already. + ]]> The exception thrown when this has been disposed. @@ -520,7 +520,7 @@ ## Remarks The countdown for the delay starts during this call. When the delay expires, this is canceled, if it has not been canceled already. - Subsequent calls to `CancelAfter` will reset the delay for this , if it has not been canceled already. + Subsequent calls to `CancelAfter` will reset the delay for this , if it has not been canceled already. ]]> The exception thrown when this has been disposed. @@ -574,6 +574,7 @@ Creates a that will be in the canceled state when the supplied token is in the canceled state. An object that's linked to the source token. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -685,6 +686,7 @@ Cancellation Task Cancellation How to: Listen for Multiple Cancellation Requests + The cancellation token was canceled. This exception is stored into the returned task. @@ -740,18 +742,18 @@ Releases all resources used by the current instance of the class. - . The `Dispose` method leaves the in an unusable state. After calling `Dispose`, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + . The `Dispose` method leaves the in an unusable state. After calling `Dispose`, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. - Note that calling `Dispose` does not communicate a request for cancellation to consumers of the associated . You can communicate a request for cancellation by calling methods such as or . + Note that calling `Dispose` does not communicate a request for cancellation to consumers of the associated . You can communicate a request for cancellation by calling methods such as or . + + For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - > [!NOTE] -> Always call `Dispose` before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's `Finalize` method. - +> Always call `Dispose` before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's `Finalize` method. + ]]> @@ -847,13 +849,13 @@ if cancellation has been requested for this ; otherwise, . - method. - - If this property returns `true`, it only guarantees that cancellation has been requested. It does not guarantee that every handler registered with the corresponding token has finished executing, nor that cancellation requests have finished propagating to all registered handlers. Additional synchronization may be required, particularly in situations where related objects are being canceled concurrently. - + method. + + If this property returns `true`, it only guarantees that cancellation has been requested. It does not guarantee that every handler registered with the corresponding token has finished executing, nor that cancellation requests have finished propagating to all registered handlers. Additional synchronization may be required, particularly in situations where related objects are being canceled concurrently. + ]]> Cancellation diff --git a/xml/System.Threading/PeriodicTimer.xml b/xml/System.Threading/PeriodicTimer.xml index 64559bbc7c5..02fd7a7239b 100644 --- a/xml/System.Threading/PeriodicTimer.xml +++ b/xml/System.Threading/PeriodicTimer.xml @@ -142,6 +142,7 @@ The behaves like an auto-reset event, in t ]]> + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Web.WebSockets/AspNetWebSocket.xml b/xml/System.Web.WebSockets/AspNetWebSocket.xml index 8cf86d3b2b1..8575e00a38c 100644 --- a/xml/System.Web.WebSockets/AspNetWebSocket.xml +++ b/xml/System.Web.WebSockets/AspNetWebSocket.xml @@ -37,11 +37,11 @@ Cancels any pending I/O operations on the object and sets the state of the object so that it cannot be used to start additional I/O operations. - method has been called, you can still access properties and methods that do not involve I/O operations. - + method has been called, you can still access properties and methods that do not involve I/O operations. + ]]> The object was previously disposed. @@ -74,25 +74,26 @@ Sends an asynchronous message to a client to close the connection. If the server initiates the request to close the connection, the method waits for the client to acknowledge the request before it returns. A reference to the operation. - and methods for both client-initiated and server-initiated requests to close an connection. The two methods handle client-initiated requests in the same way: After the client sends a message to the server to close the connection, the server calls one of these methods and sends an acknowledgment to the client, and then the method returns. - - For server-initiated requests, the two methods work differently. The method sends a message to the client to close the connection, waits for a response, and then returns. The server does not wait for any additional data sent by the client. In contrast, the method sends a message to the client to close the connection and returns without waiting for a response. After the method returns, you can call the method and handle either additional data or the acknowledgment that the client sends. - + and methods for both client-initiated and server-initiated requests to close an connection. The two methods handle client-initiated requests in the same way: After the client sends a message to the server to close the connection, the server calls one of these methods and sends an acknowledgment to the client, and then the method returns. + + For server-initiated requests, the two methods work differently. The method sends a message to the client to close the connection, waits for a response, and then returns. The server does not wait for any additional data sent by the client. In contrast, the method sends a message to the client to close the connection and returns without waiting for a response. After the method returns, you can call the method and handle either additional data or the acknowledgment that the client sends. + ]]> The object was previously disposed. - The object is in an aborted state. - - -or- - - Sending operations are unavailable. - - -or- - + The object is in an aborted state. + + -or- + + Sending operations are unavailable. + + -or- + Receiving operations are unavailable. + The cancellation token was canceled. This exception is stored into the returned task. @@ -122,21 +123,22 @@ Sends an asynchronous message to a client to close the connection. If the server initiates the request to close the connection, the method returns without waiting for a response. A reference to the operation. - and methods for both client-initiated and server-initiated requests to close an connection. The two methods handle client-initiated requests in the same way: After the client sends a message to the server to close the connection, the server calls one of these methods and sends an acknowledgment to the client, and then the method returns. - - For server-initiated requests, the two methods work differently. The method sends a message to the client to close the connection, waits for a response, and then returns. The server does not wait for any additional data sent by the client. In contrast, the method sends a message to the client to close the connection and returns without waiting for a response. After the method returns, you can call the method and handle either additional data or the acknowledgment that the client sends. - + and methods for both client-initiated and server-initiated requests to close an connection. The two methods handle client-initiated requests in the same way: After the client sends a message to the server to close the connection, the server calls one of these methods and sends an acknowledgment to the client, and then the method returns. + + For server-initiated requests, the two methods work differently. The method sends a message to the client to close the connection, waits for a response, and then returns. The server does not wait for any additional data sent by the client. In contrast, the method sends a message to the client to close the connection and returns without waiting for a response. After the method returns, you can call the method and handle either additional data or the acknowledgment that the client sends. + ]]> The object was previously disposed. - The object is in an aborted state. - - -or- - + The object is in an aborted state. + + -or- + Sending operations are unavailable. + The cancellation token was canceled. This exception is stored into the returned task. @@ -202,11 +204,11 @@ Releases all resources used by an object. - method on a object to release any resources that remain after your code has finished executing. - + method on a object to release any resources that remain after your code has finished executing. + ]]> @@ -237,11 +239,12 @@ A reference to the task of receiving a message. To be added. The object was previously disposed. - The object is in an aborted state. - - -or- - + The object is in an aborted state. + + -or- + Receiving operations are unavailable. + The cancellation token was canceled. This exception is stored into the returned task. @@ -275,11 +278,12 @@ A reference to the task of sending a message. To be added. The object is disposed. - The object is in an aborted state. - - -or- - + The object is in an aborted state. + + -or- + Sending operations are unavailable. + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Windows.Threading/Dispatcher.xml b/xml/System.Windows.Threading/Dispatcher.xml index 98940368755..35b281498b5 100644 --- a/xml/System.Windows.Threading/Dispatcher.xml +++ b/xml/System.Windows.Threading/Dispatcher.xml @@ -21,42 +21,42 @@ Provides services for managing the queue of work items for a thread. - maintains a prioritized queue of work items for a specific thread. - - When a is created on a thread, it becomes the only that can be associated with the thread, even if the is shut down. - - If you attempt to get the for the current thread and a is not associated with the thread, a will be created. A is also created when you create a . If you create a on a background thread, be sure to shut down the dispatcher before exiting the thread. - - If a is shut down, it cannot be restarted. - - In WPF, a can only be accessed by the it is associated with. For example, a background thread cannot update the contents of a that is associated with the on the UI thread. In order for the background thread to access the property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the queue of the at the specified . - - If is called on a that has shut down, the status property of the returned is set to . - - All of the methods on , with the exception of , are free-threaded. - - Objects that derive from have thread affinity. - - Objects that derive from are free-threaded when they are frozen. For more information, see [Freezable Objects Overview](/dotnet/framework/wpf/advanced/freezable-objects-overview). - - - -## Examples - The following example shows how to place an operation onto a . For the full source code of this example, see [Single-Threaded Application with Long-Running Calculation Sample](https://go.microsoft.com/fwlink/?LinkID=160038). - - First, a delegate is created that accepts no arguments. - - :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Overview/Window1.xaml.cs" id="Snippetthreadingprimenumberinit"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingPrimeNumbers/visualbasic/mainwindow.xaml.vb" id="Snippetthreadingprimenumberinit"::: - - Next, is called. This call to takes two parameters: the priority, which is set to , and the callback, which is passed in through an instance of the delegate `NextPrimeDelegate`. - - :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Overview/Window1.xaml.cs" id="Snippetthreadingprimenumberbegininvoke"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingPrimeNumbers/visualbasic/mainwindow.xaml.vb" id="Snippetthreadingprimenumberbegininvoke"::: - + maintains a prioritized queue of work items for a specific thread. + + When a is created on a thread, it becomes the only that can be associated with the thread, even if the is shut down. + + If you attempt to get the for the current thread and a is not associated with the thread, a will be created. A is also created when you create a . If you create a on a background thread, be sure to shut down the dispatcher before exiting the thread. + + If a is shut down, it cannot be restarted. + + In WPF, a can only be accessed by the it is associated with. For example, a background thread cannot update the contents of a that is associated with the on the UI thread. In order for the background thread to access the property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the queue of the at the specified . + + If is called on a that has shut down, the status property of the returned is set to . + + All of the methods on , with the exception of , are free-threaded. + + Objects that derive from have thread affinity. + + Objects that derive from are free-threaded when they are frozen. For more information, see [Freezable Objects Overview](/dotnet/framework/wpf/advanced/freezable-objects-overview). + + + +## Examples + The following example shows how to place an operation onto a . For the full source code of this example, see [Single-Threaded Application with Long-Running Calculation Sample](https://go.microsoft.com/fwlink/?LinkID=160038). + + First, a delegate is created that accepts no arguments. + + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Overview/Window1.xaml.cs" id="Snippetthreadingprimenumberinit"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingPrimeNumbers/visualbasic/mainwindow.xaml.vb" id="Snippetthreadingprimenumberinit"::: + + Next, is called. This call to takes two parameters: the priority, which is set to , and the callback, which is passed in through an instance of the delegate `NextPrimeDelegate`. + + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Overview/Window1.xaml.cs" id="Snippetthreadingprimenumberbegininvoke"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingPrimeNumbers/visualbasic/mainwindow.xaml.vb" id="Snippetthreadingprimenumberbegininvoke"::: + ]]> Single-Threaded Application with Long-Running Calculation Sample @@ -70,29 +70,29 @@ Executes a delegate asynchronously on the thread the is associated with. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is asynchronous; therefore, control returns immediately to the calling object after it is called. - - returns a object that can be used to interact with the delegate when the delegate is in the event queue. - - The object returned by can be used in several ways to interact with the specified delegate, such as: - -- Changing the of the delegate as it is pending execution in the event queue. - -- Removing the delegate from the event queue. - -- Waiting for the delegate to return. - -- Obtaining the value that the delegate returns after it is executed. - - If multiple calls are made at the same , they will be executed in the order the calls were made. - - If is called on a that has shut down, the status property of the returned is set to . - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is asynchronous; therefore, control returns immediately to the calling object after it is called. + + returns a object that can be used to interact with the delegate when the delegate is in the event queue. + + The object returned by can be used in several ways to interact with the specified delegate, such as: + +- Changing the of the delegate as it is pending execution in the event queue. + +- Removing the delegate from the event queue. + +- Waiting for the delegate to return. + +- Obtaining the value that the delegate returns after it is executed. + + If multiple calls are made at the same , they will be executed in the order the calls were made. + + If is called on a that has shut down, the status property of the returned is set to . + ]]> @@ -139,25 +139,25 @@ Executes the specified delegate asynchronously with the specified arguments on the thread that the was created on. An object, which is returned immediately after is called, that can be used to interact with the delegate as it is pending execution in the event queue. - object returned by can be used in several ways to interact with the specified delegate, such as: - -- Changing the of the delegate as it is pending execution in the event queue. - -- Removing the delegate from the event queue. - -- Waiting for the delegate to return. - -- Obtaining the value that the delegate returns after it is executed. - - is asynchronous; therefore, control returns immediately to the calling object after it is called. - - In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - If is called on a that has shut down, the status property of the returned is set to . - + object returned by can be used in several ways to interact with the specified delegate, such as: + +- Changing the of the delegate as it is pending execution in the event queue. + +- Removing the delegate from the event queue. + +- Waiting for the delegate to return. + +- Obtaining the value that the delegate returns after it is executed. + + is asynchronous; therefore, control returns immediately to the calling object after it is called. + + In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + If is called on a that has shut down, the status property of the returned is set to . + ]]> @@ -205,44 +205,44 @@ Executes the specified delegate asynchronously at the specified priority on the thread the is associated with. An object, which is returned immediately after is called, that can be used to interact with the delegate as it is pending execution in the event queue. - calls are made at the same , they will be executed in the order the calls were made. - - returns a object that can be used to interact with the delegate when the delegate is in the event queue. - - The object returned by can be used in several ways to interact with the specified delegate, such as: - -- Changing the of the delegate as it is pending execution in the event queue. - -- Removing the delegate from the event queue. - -- Waiting for the delegate to return. - -- Obtaining the value that the delegate returns after it is executed. - - is asynchronous; therefore, control returns immediately to the calling object after it is called. - - In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - If is called on a that has shut down, the status property of the returned is set to . - - - -## Examples - The following example shows how to place an operation onto a . For the full source code of this example, see [Single-Threaded Application with Long-Running Calculation Sample](https://go.microsoft.com/fwlink/?LinkID=160038). - - First, a delegate is created that accepts no arguments. - - :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Overview/Window1.xaml.cs" id="Snippetthreadingprimenumberinit"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingPrimeNumbers/visualbasic/mainwindow.xaml.vb" id="Snippetthreadingprimenumberinit"::: - - Next, is called. Because every has a property that returns the it is associated with, the desired is obtained by querying the , in this case a named `startStopButton`. The call to takes two parameters: the priority, which is set to , and the callback, which is passed in through an instance of the delegate `NextPrimeDelegate`. - - :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Overview/Window1.xaml.cs" id="Snippetthreadingprimenumberbegininvoke"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingPrimeNumbers/visualbasic/mainwindow.xaml.vb" id="Snippetthreadingprimenumberbegininvoke"::: - + calls are made at the same , they will be executed in the order the calls were made. + + returns a object that can be used to interact with the delegate when the delegate is in the event queue. + + The object returned by can be used in several ways to interact with the specified delegate, such as: + +- Changing the of the delegate as it is pending execution in the event queue. + +- Removing the delegate from the event queue. + +- Waiting for the delegate to return. + +- Obtaining the value that the delegate returns after it is executed. + + is asynchronous; therefore, control returns immediately to the calling object after it is called. + + In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + If is called on a that has shut down, the status property of the returned is set to . + + + +## Examples + The following example shows how to place an operation onto a . For the full source code of this example, see [Single-Threaded Application with Long-Running Calculation Sample](https://go.microsoft.com/fwlink/?LinkID=160038). + + First, a delegate is created that accepts no arguments. + + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Overview/Window1.xaml.cs" id="Snippetthreadingprimenumberinit"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingPrimeNumbers/visualbasic/mainwindow.xaml.vb" id="Snippetthreadingprimenumberinit"::: + + Next, is called. Because every has a property that returns the it is associated with, the desired is obtained by querying the , in this case a named `startStopButton`. The call to takes two parameters: the priority, which is set to , and the callback, which is passed in through an instance of the delegate `NextPrimeDelegate`. + + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Overview/Window1.xaml.cs" id="Snippetthreadingprimenumberbegininvoke"::: + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingPrimeNumbers/visualbasic/mainwindow.xaml.vb" id="Snippetthreadingprimenumberbegininvoke"::: + ]]> @@ -296,25 +296,25 @@ Executes the specified delegate asynchronously with the specified arguments, at the specified priority, on the thread that the was created on. An object, which is returned immediately after is called, that can be used to interact with the delegate as it is pending execution in the event queue. - object returned by can be used in several ways to interact with the specified delegate, such as: - -- Changing the of the delegate as it is pending execution in the event queue. - -- Removing the delegate from the event queue. - -- Waiting for the delegate to return. - -- Obtaining the value that the delegate returns after it is executed. - - is asynchronous; therefore, control returns immediately to the calling object after it is called. - - In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - If is called on a that has shut down, the status property of the returned is set to . - + object returned by can be used in several ways to interact with the specified delegate, such as: + +- Changing the of the delegate as it is pending execution in the event queue. + +- Removing the delegate from the event queue. + +- Waiting for the delegate to return. + +- Obtaining the value that the delegate returns after it is executed. + + is asynchronous; therefore, control returns immediately to the calling object after it is called. + + In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + If is called on a that has shut down, the status property of the returned is set to . + ]]> @@ -364,44 +364,44 @@ Executes the specified delegate asynchronously at the specified priority and with the specified argument on the thread the is associated with. An object, which is returned immediately after is called, that can be used to interact with the delegate as it is pending execution in the event queue. - returns a object that can be used to interact with the delegate when the delegate is in the event queue. - - The object returned by can be used in several ways to interact with the specified delegate, such as: - -- Changing the of the delegate as it is pending execution in the event queue. - -- Removing the delegate from the event queue. - -- Waiting for the delegate to return. - -- Obtaining the value that the delegate returns after it is executed. - - is asynchronous; therefore, control returns immediately to the calling object after it is called. - - In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - If multiple calls are made at the same , they will be executed in the order the calls were made. - + returns a object that can be used to interact with the delegate when the delegate is in the event queue. + + The object returned by can be used in several ways to interact with the specified delegate, such as: + +- Changing the of the delegate as it is pending execution in the event queue. + +- Removing the delegate from the event queue. + +- Waiting for the delegate to return. + +- Obtaining the value that the delegate returns after it is executed. + + is asynchronous; therefore, control returns immediately to the calling object after it is called. + + In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + If multiple calls are made at the same , they will be executed in the order the calls were made. + If is called on a that has shut down, the status property of the returned is set to . - -## Examples - The following example shows how to place an operation onto a . - - First, a delegate is created that accepts one argument, in this case a string. - + +## Examples + The following example shows how to place an operation onto a . + + First, a delegate is created that accepts one argument, in this case a string. + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/BeginInvoke/Window1.xaml.cs" id="Snippetthreadingweatherdelegates"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingWeatherForecast/visualbasic/window1.xaml.vb" id="Snippetthreadingweatherdelegates"::: - - Next, is called. Because every has a property that returns the it is associated with, the desired is obtained by querying the , in this case a named `tomorrowsWeather`. The call to takes three parameters: the priority, which is set to ; the callback, which is passed in through an instance of the delegate `OneArgDelegate`; and a string named `weather`, which is the argument for the callback. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingWeatherForecast/visualbasic/window1.xaml.vb" id="Snippetthreadingweatherdelegates"::: + + Next, is called. Because every has a property that returns the it is associated with, the desired is obtained by querying the , in this case a named `tomorrowsWeather`. The call to takes three parameters: the priority, which is set to ; the callback, which is passed in through an instance of the delegate `OneArgDelegate`; and a string named `weather`, which is the argument for the callback. + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/BeginInvoke/Window1.xaml.cs" id="Snippetthreadingweatherdispatcheronearge"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingWeatherForecast/visualbasic/window1.xaml.vb" id="Snippetthreadingweatherdispatcheronearge"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/ThreadingWeatherForecast/visualbasic/window1.xaml.vb" id="Snippetthreadingweatherdispatcheronearge"::: + ]]> @@ -461,31 +461,31 @@ Executes the specified delegate asynchronously at the specified priority and with the specified array of arguments on the thread the is associated with. An object, which is returned immediately after is called, that can be used to interact with the delegate as it is pending execution in the queue. - returns a object that can be used to interact with the delegate when the delegate is in the event queue. - - The object returned by can be used in several ways to interact with the specified delegate, such as: - -- Changing the of the delegate as it is pending execution in the event queue. - -- Removing the delegate from the event queue. - -- Waiting for the delegate to return. - -- Obtaining the value that the delegate returns after it is executed. - - is asynchronous; therefore, control returns immediately to the calling object after it is called. - - In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - If multiple calls are made at the same , they will be executed in the order the calls were made. - - If is called on a that has shut down, the status property of the returned is set to . - + returns a object that can be used to interact with the delegate when the delegate is in the event queue. + + The object returned by can be used in several ways to interact with the specified delegate, such as: + +- Changing the of the delegate as it is pending execution in the event queue. + +- Removing the delegate from the event queue. + +- Waiting for the delegate to return. + +- Obtaining the value that the delegate returns after it is executed. + + is asynchronous; therefore, control returns immediately to the calling object after it is called. + + In WPF, only the thread that created a may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + If multiple calls are made at the same , they will be executed in the order the calls were made. + + If is called on a that has shut down, the status property of the returned is set to . + ]]> @@ -527,19 +527,19 @@ The priority at which to begin shutting down the dispatcher. Initiates shutdown of the asynchronously. - demands unrestricted UI Permissions. - - When the starts to shut down, the event is raised and is set to `true`. - - The does not shut down completely until the event queue unwinds. - - When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. - - Once the shutdown process begins, all pending work items in the queue are aborted. - + demands unrestricted UI Permissions. + + When the starts to shut down, the event is raised and is set to `true`. + + The does not shut down completely until the event queue unwinds. + + When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. + + Once the shutdown process begins, all pending work items in the queue are aborted. + ]]> @@ -575,21 +575,21 @@ if the calling thread is the thread associated with this ; otherwise, . - that a is created on may access the object. Use or to access the object from a different thread. - - can be called from any thread. - + that a is created on may access the object. Use or to access the object from a different thread. + + can be called from any thread. + The difference between and is returns a Boolean indicating whether the calling thread has access to the and throws an exception. - -## Examples - The following example uses to determine whether a thread has access to a . The method on the associated with the is called to verify access to the thread. If the calling thread has access to the , the is updated by accessing the members of the ; otherwise, a delegate, which accepts a as an argument, is placed onto the . The will delegate the work of updating the . - + +## Examples + The following example uses to determine whether a thread has access to a . The method on the associated with the is called to verify access to the thread. If the calling thread has access to the , the is updated by accessing the members of the ; otherwise, a delegate, which accepts a as an argument, is placed onto the . The will delegate the work of updating the . + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/CheckAccess/Window1.xaml.cs" id="Snippetdispatcheraccesscheckaccess"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/DispatcherAccessSample/visualbasic/window1.xaml.vb" id="Snippetdispatcheraccesscheckaccess"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/DispatcherAccessSample/visualbasic/window1.xaml.vb" id="Snippetdispatcheraccesscheckaccess"::: + ]]> @@ -618,11 +618,11 @@ Gets the for the thread currently executing and creates a new if one is not already associated with the thread. The dispatcher associated with the current thread. - is not associated with the current thread, a new will be created. This is not the case with the method. will return `null` if there is not a dispatcher associated with the specified thread. - + is not associated with the current thread, a new will be created. This is not the case with the method. will return `null` if there is not a dispatcher associated with the specified thread. + ]]> @@ -651,29 +651,29 @@ Disables processing of the queue. A structure used to re-enable dispatcher processing. - objects are not allowed to be pushed. - -- Message processing is not permitted. - - The structure that returns when it is called can be used to re-enable dispatcher processing. Calling on the structure re-enables processing. - + objects are not allowed to be pushed. + +- Message processing is not permitted. + + The structure that returns when it is called can be used to re-enable dispatcher processing. Calling on the structure re-enables processing. + can only be called on the thread the is associated with. - -## Examples - The following example shows how to disable dispatcher processing and re-enable dispatcher processing. is called in a **using** statement. returns a structure that is used as the object to be disposed when the **using** block finishes. When is called on the structure, dispatcher processing is re-enabled. - + +## Examples + The following example shows how to disable dispatcher processing and re-enable dispatcher processing. is called in a **using** statement. returns a structure that is used as the object to be disposed when the **using** block finishes. When is called on the structure, dispatcher processing is re-enabled. + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/DisableProcessing/Window1.xaml.cs" id="Snippetdispatcherdisableprocessing"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/DispatcherSnippets/visualbasic/window1.xaml.vb" id="Snippetdispatcherdisableprocessing"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/DispatcherSnippets/visualbasic/window1.xaml.vb" id="Snippetdispatcherdisableprocessing"::: + ]]> @@ -738,13 +738,13 @@ Gets the for the specified thread. The dispatcher for . - does not create a on a thread that does not have a . A new is created on a thread that does not already have a when attempting to get the by using the property. - + does not create a on a thread that does not have a . A new is created on a thread that does not already have a when attempting to get the by using the property. + ]]> @@ -779,17 +779,17 @@ if the dispatcher has finished shutting down; otherwise, . - starts to shut down, the event is raised and is set to `true`. - - The does not shutdown completely until the event queue unwinds. - - When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. - - Once the shutdown process begins, all pending work items in the queue are aborted. - + starts to shut down, the event is raised and is set to `true`. + + The does not shutdown completely until the event queue unwinds. + + When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. + + Once the shutdown process begins, all pending work items in the queue are aborted. + ]]> @@ -824,17 +824,17 @@ if the has started shutting down; otherwise, . - starts to shut down, the event is raised and is set to `true`. - - The does not shut down completely until the event queue unwinds. - - When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. - - Once the shutdown process begins, all pending work items in the queue are aborted. - + starts to shut down, the event is raised and is set to `true`. + + The does not shut down completely until the event queue unwinds. + + When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. + + Once the shutdown process begins, all pending work items in the queue are aborted. + ]]> @@ -872,11 +872,11 @@ Gets the collection of hooks that provide additional event information about the . The hooks associated with this . - class provides additional event information about the , such as when the is inactive or when an operation has competed. - + class provides additional event information about the , such as when the is inactive or when an operation has competed. + ]]> @@ -889,19 +889,19 @@ Executes the specified delegate synchronously on the thread the is associated with. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - -## Examples - The following example places a delegate onto a at using . - + +## Examples + The following example places a delegate onto a at using . + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Invoke/Window1.xaml.cs" id="Snippetsystemtimerdispatcherinvoke"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/InvalidateRequeryWithSystemTimer/visualbasic/window1.xaml.vb" id="Snippetsystemtimerdispatcherinvoke"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/InvalidateRequeryWithSystemTimer/visualbasic/window1.xaml.vb" id="Snippetsystemtimerdispatcherinvoke"::: + ]]> @@ -1006,13 +1006,13 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate with the specified arguments synchronously on the thread the is associated with. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. + ]]> @@ -1056,19 +1056,19 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate synchronously at the specified priority on the thread that the is associated with. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - -## Examples - The following example places a delegate onto a at using . - + +## Examples + The following example places a delegate onto a at using . + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/Invoke/Window1.xaml.cs" id="Snippetsystemtimerdispatcherinvoke"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/InvalidateRequeryWithSystemTimer/visualbasic/window1.xaml.vb" id="Snippetsystemtimerdispatcherinvoke"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/InvalidateRequeryWithSystemTimer/visualbasic/window1.xaml.vb" id="Snippetsystemtimerdispatcherinvoke"::: + ]]> @@ -1108,6 +1108,7 @@ The default priority is `DispatcherPriority.Send`. An object that indicates whether to cancel the action. Executes the specified synchronously at the specified priority on the thread the is associated with. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1154,13 +1155,13 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate within the designated time span at the specified priority with the specified arguments synchronously on the thread the is associated with. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is a synchronous operation; therefore, control won't return to the calling object until after the callback returns. - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is a synchronous operation; therefore, control won't return to the calling object until after the callback returns. + ]]> @@ -1207,13 +1208,13 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the is associated with. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. + ]]> @@ -1259,15 +1260,15 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate at the specified priority with the specified argument synchronously on the thread the is associated with. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. + ]]> @@ -1323,13 +1324,13 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate synchronously at the specified priority and with the specified time-out value on the thread the was created. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. + ]]> @@ -1385,6 +1386,7 @@ The default priority is `DispatcherPriority.Send`. is a negative number other than -1, and this method was invoked across threads. is not a valid priority. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1433,13 +1435,13 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate within the designated time span at the specified priority with the specified arguments synchronously on the thread the is associated with. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. + ]]> @@ -1502,15 +1504,15 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the is associated with. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. + ]]> @@ -1568,15 +1570,15 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate at the specified priority with the specified argument synchronously on the thread the is associated with. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. + ]]> @@ -1639,15 +1641,15 @@ The default priority is `DispatcherPriority.Send`. Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the is associated with. The return value from the delegate being invoked or if the delegate has no return value. - may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . - - is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. - + may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a that was created on the UI thread. In order for the background thread to access the Content property of the , the background thread must delegate the work to the associated with the UI thread. This is accomplished by using either or . is synchronous and is asynchronous. The operation is added to the event queue of the at the specified . + + is a synchronous operation; therefore, control will not return to the calling object until after the callback returns. + ]]> @@ -1760,6 +1762,7 @@ The default priority is `DispatcherPriority.Send`. Executes the specified synchronously at the specified priority on the thread the is associated with. The value returned by . To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1810,6 +1813,7 @@ The default priority is `DispatcherPriority.Send`. is a negative number other than -1, and the method was invoked across threads. is not a valid priority. + The cancellation token was canceled. This exception is stored into the returned task. @@ -1925,6 +1929,7 @@ This method stores in the task it returns all non-usage exceptions that the meth Executes the specified asynchronously at the specified priority on the thread the is associated with. An object, which is returned immediately after is called, that can be used to interact with the delegate as it is pending execution in the event queue. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -2033,6 +2038,7 @@ This method stores in the task it returns all non-usage exceptions that the meth Executes the specified asynchronously at the specified priority on the thread the is associated with. An object, which is returned immediately after is called, that can be used to interact with the delegate as it is pending execution in the event queue. To be added. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2064,19 +2070,19 @@ This method stores in the task it returns all non-usage exceptions that the meth Initiates the shutdown process of the synchronously. - demands unrestricted UI Permissions. - - When the starts to shut down, the event is raised and is set to `true`. - - The does not shut down completely until the event queue unwinds. - - When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. - - Once the shutdown process begins, all pending work items in the queue are aborted. - + demands unrestricted UI Permissions. + + When the starts to shut down, the event is raised and is set to `true`. + + The does not shut down completely until the event queue unwinds. + + When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. + + Once the shutdown process begins, all pending work items in the queue are aborted. + ]]> @@ -2113,36 +2119,36 @@ This method stores in the task it returns all non-usage exceptions that the meth The frame for the dispatcher to process. Enters an execute loop. - represents a loop that processes pending work items. - - The Dispatcher processes the work item queue in a loop. The loop is referred to as a frame. The initial loop is typically initiated by the application by calling . - - enters a loop represented by the parameter `frame`. At each iteration of the loop, the will check the property on the class to determine whether the loop should continue or if it should stop. - + represents a loop that processes pending work items. + + The Dispatcher processes the work item queue in a loop. The loop is referred to as a frame. The initial loop is typically initiated by the application by calling . + + enters a loop represented by the parameter `frame`. At each iteration of the loop, the will check the property on the class to determine whether the loop should continue or if it should stop. + allows for the property to be set explicitly and it respects the property on the . This means when the starts to shut down, frames that use the default implementation will exit, which enables all nested frames to exit. - -## Examples - The following example shows how to use a to achieve similar results as the Windows Forms method. - + +## Examples + The following example shows how to use a to achieve similar results as the Windows Forms method. + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/DisableProcessing/Window1.xaml.cs" id="Snippetdispatcherdispatcherframedoevents"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/DispatcherSnippets/visualbasic/window1.xaml.vb" id="Snippetdispatcherdispatcherframedoevents"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/DispatcherSnippets/visualbasic/window1.xaml.vb" id="Snippetdispatcherdispatcherframedoevents"::: + ]]> is . - is - - -or- - - is running on a different . - - -or- - + is + + -or- + + is running on a different . + + -or- + Dispatcher processing has been disabled. @@ -2176,13 +2182,13 @@ This method stores in the task it returns all non-usage exceptions that the meth Pushes the main execution frame on the event queue of the . - processes the event queue in a loop. The loop is referred to as a frame. The initial loop is typically initiated by the application by calling . - - The main execution frame will continue until the is shutdown. - + processes the event queue in a loop. The loop is referred to as a frame. The initial loop is typically initiated by the application by calling . + + The main execution frame will continue until the is shutdown. + ]]> @@ -2210,17 +2216,17 @@ This method stores in the task it returns all non-usage exceptions that the meth Occurs when the finishes shutting down. - is started, the event is raised and is set to `true`. - - The does not shutdown completely until the event queue unwinds. - - When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. - - Once the shutdown process begins, all pending work items in the queue are aborted. - + is started, the event is raised and is set to `true`. + + The does not shutdown completely until the event queue unwinds. + + When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. + + Once the shutdown process begins, all pending work items in the queue are aborted. + ]]> @@ -2252,17 +2258,17 @@ This method stores in the task it returns all non-usage exceptions that the meth Occurs when the begins to shut down. - is started, the event is raised and is set to `true`. - - The does not shutdown completely until the event queue unwinds. - - When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. - - Once the shutdown process begins, all pending work items in the queue are aborted. - + is started, the event is raised and is set to `true`. + + The does not shutdown completely until the event queue unwinds. + + When the Dispatcher finishes shutting down, the event is raised and the property is set to `true`. + + Once the shutdown process begins, all pending work items in the queue are aborted. + ]]> @@ -2325,17 +2331,17 @@ This method stores in the task it returns all non-usage exceptions that the meth Occurs when a thread exception is thrown and uncaught during execution of a delegate by way of or . - or is uncaught. - - A handler can mark the exception as handled, which will prevent the internal exception handler from being called. - - Event handlers for this event must be written with care to avoid creating secondary exceptions and to catch any that occur. It is recommended to avoid allocating memory or doing any resource intensive operations in the handler. - - The event provides a means to not raise the event. The event is raised first, and If on the is set to `false`, the event will not be raised. - + or is uncaught. + + A handler can mark the exception as handled, which will prevent the internal exception handler from being called. + + Event handlers for this event must be written with care to avoid creating secondary exceptions and to catch any that occur. It is recommended to avoid allocating memory or doing any resource intensive operations in the handler. + + The event provides a means to not raise the event. The event is raised first, and If on the is set to `false`, the event will not be raised. + ]]> @@ -2374,17 +2380,17 @@ This method stores in the task it returns all non-usage exceptions that the meth Occurs when a thread exception is thrown and uncaught during execution of a delegate by way of or when in the filter stage. - or and is uncaught. - - The call stack is not unwound at this point (first-chance exception). - - Event handlers for this event must be written with care to avoid creating secondary exceptions and to catch any that occur. It is recommended to avoid allocating memory or doing any resource intensive operations in the handler. - - The event provides a means to not raise the event. The event is raised first, and If on the is set to `false`, the event will not be raised. - + or and is uncaught. + + The call stack is not unwound at this point (first-chance exception). + + Event handlers for this event must be written with care to avoid creating secondary exceptions and to catch any that occur. It is recommended to avoid allocating memory or doing any resource intensive operations in the handler. + + The event provides a means to not raise the event. The event is raised first, and If on the is set to `false`, the event will not be raised. + ]]> @@ -2452,25 +2458,25 @@ This method stores in the task it returns all non-usage exceptions that the meth Determines whether the calling thread has access to this . - is created on may access the . - - This method is public; therefore, any thread can check to see whether it has access to the . - + is created on may access the . + + This method is public; therefore, any thread can check to see whether it has access to the . + The difference between and is returns a Boolean if the calling thread does not have access to the and throws an exception. - -## Examples - The following example uses to determine whether a thread has access to the thread that a was created on. The method takes an object as an argument, which is cast to a . The method on the of the is called to verify access to the thread. - - If the calling thread has access to the , the is updated by just accessing the members of the . - - If the calling thread does not have access, an is thrown. This example catches the exception and pushes a delegate, which accepts a as an argument, onto the of the . This will do the work of updating the . - + +## Examples + The following example uses to determine whether a thread has access to the thread that a was created on. The method takes an object as an argument, which is cast to a . The method on the of the is called to verify access to the thread. + + If the calling thread has access to the , the is updated by just accessing the members of the . + + If the calling thread does not have access, an is thrown. This example catches the exception and pushes a delegate, which accepts a as an argument, onto the of the . This will do the work of updating the . + :::code language="csharp" source="~/snippets/csharp/System.Windows.Threading/Dispatcher/CheckAccess/Window1.xaml.cs" id="Snippetdispatcheraccessverifyaccess"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/DispatcherAccessSample/visualbasic/window1.xaml.vb" id="Snippetdispatcheraccessverifyaccess"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Wpf/DispatcherAccessSample/visualbasic/window1.xaml.vb" id="Snippetdispatcheraccessverifyaccess"::: + ]]> The calling thread does not have access to this . @@ -2509,13 +2515,13 @@ This method stores in the task it returns all non-usage exceptions that the meth Creates an awaitable object that asynchronously yields control back to the current dispatcher and provides an opportunity for the dispatcher to process other events. An awaitable object that asynchronously yields control back to the current dispatcher and provides an opportunity for the dispatcher to process other events. - method and passing in . - + method and passing in . + ]]> @@ -2546,11 +2552,11 @@ This method stores in the task it returns all non-usage exceptions that the meth Creates an awaitable object that asynchronously yields control back to the current dispatcher and provides an opportunity for the dispatcher to process other events. The work that occurs when control returns to the code awaiting the result of this method is scheduled with the specified priority. An awaitable object that asynchronously yields control back to the current dispatcher and provides an opportunity for the dispatcher to process other events. - diff --git a/xml/System.Xml.Linq/XCData.xml b/xml/System.Xml.Linq/XCData.xml index e9408a09d13..ff3b40d877e 100644 --- a/xml/System.Xml.Linq/XCData.xml +++ b/xml/System.Xml.Linq/XCData.xml @@ -40,13 +40,13 @@ Represents a text node that contains CDATA. - , which represents XML text. CDATA sections are special cases of XML text. - + , which represents XML text. CDATA sections are special cases of XML text. + ]]> LINQ to XML overview @@ -107,31 +107,31 @@ A string that contains the value of the node. Initializes a new instance of the class. - - - -Console.WriteLine(root) -``` - - This example produces the following output: - -``` - -``` - + + + +Console.WriteLine(root) +``` + + This example produces the following output: + +``` + +``` + ]]> LINQ to XML overview @@ -180,11 +180,11 @@ Console.WriteLine(root) The node to copy from. Initializes a new instance of the class. - LINQ to XML overview @@ -227,78 +227,78 @@ Console.WriteLine(root) Gets the node type for this node. The node type. For objects, this value is . - contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. - - - -## Examples - The following example creates an XML tree that contains various types of nodes. It then iterates through the tree, and prints the node type of each node. - -```csharp -// Note that XNode uses XmlNodeType, which is in the System.Xml namespace. -XDocument xmlTree = new XDocument( - new XComment("a comment"), - new XProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"hello.xsl\""), - new XElement("Root", - new XAttribute("Att", "attContent"), - new XElement("Child1", - new XCData("CDATA content") - ), - new XElement("Child2", - new XText("Text content") - ) - ) -); - -foreach (XNode node in xmlTree.DescendantNodes()) -{ - Console.WriteLine(node.NodeType); - if (node.NodeType == XmlNodeType.Element) - { - foreach (XAttribute att in ((XElement)node).Attributes()) - Console.WriteLine(att.NodeType); - } -} -``` - -```vb -Dim xmlTree As XDocument = _ - - - - - - Text content - - -' Note that XNode uses XmlNodeType, which is in the System.Xml namespace. -For Each node As XNode In xmlTree.DescendantNodes - Console.WriteLine(node.NodeType.ToString()) - If node.NodeType = XmlNodeType.Element Then - For Each att In DirectCast(node, XElement).Attributes - Console.WriteLine(att.NodeType.ToString()) - Next - End If -Next - -``` - - This example produces the following output: - -``` -Comment -ProcessingInstruction -Element -Attribute -Element -CDATA -Element -Text -``` - + contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. + + + +## Examples + The following example creates an XML tree that contains various types of nodes. It then iterates through the tree, and prints the node type of each node. + +```csharp +// Note that XNode uses XmlNodeType, which is in the System.Xml namespace. +XDocument xmlTree = new XDocument( + new XComment("a comment"), + new XProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"hello.xsl\""), + new XElement("Root", + new XAttribute("Att", "attContent"), + new XElement("Child1", + new XCData("CDATA content") + ), + new XElement("Child2", + new XText("Text content") + ) + ) +); + +foreach (XNode node in xmlTree.DescendantNodes()) +{ + Console.WriteLine(node.NodeType); + if (node.NodeType == XmlNodeType.Element) + { + foreach (XAttribute att in ((XElement)node).Attributes()) + Console.WriteLine(att.NodeType); + } +} +``` + +```vb +Dim xmlTree As XDocument = _ + + + + + + Text content + + +' Note that XNode uses XmlNodeType, which is in the System.Xml namespace. +For Each node As XNode In xmlTree.DescendantNodes + Console.WriteLine(node.NodeType.ToString()) + If node.NodeType = XmlNodeType.Element Then + For Each att In DirectCast(node, XElement).Attributes + Console.WriteLine(att.NodeType.ToString()) + Next + End If +Next + +``` + + This example produces the following output: + +``` +Comment +ProcessingInstruction +Element +Attribute +Element +CDATA +Element +Text +``` + ]]> @@ -346,11 +346,11 @@ Text An into which this method will write. Writes this CDATA object to an . - . - + . + ]]> LINQ to XML overview @@ -394,6 +394,7 @@ Text Writes this to the given . A task representing the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Xml.Linq/XComment.xml b/xml/System.Xml.Linq/XComment.xml index 607f88eb3ce..5150e5b2a27 100644 --- a/xml/System.Xml.Linq/XComment.xml +++ b/xml/System.Xml.Linq/XComment.xml @@ -40,11 +40,11 @@ Represents an XML comment. - as a sibling of the root element node. - + as a sibling of the root element node. + ]]> @@ -100,33 +100,33 @@ A string that contains the contents of the new object. Initializes a new instance of the class with the specified string content. - - - -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - - - -``` - + + + +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + + + +``` + ]]> The parameter is . @@ -170,11 +170,11 @@ Console.WriteLine(root) The node to copy from. Initializes a new instance of the class from an existing comment node. - The parameter is . @@ -218,34 +218,34 @@ Console.WriteLine(root) Gets the node type for this node. The node type. For objects, this value is . - contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. - - - -## Examples - The following example creates a comment node and prints its node type. - -```csharp -XComment com = new XComment("This is a comment"); -XNode node = com; -Console.WriteLine(node.NodeType); -``` - -```vb -Dim com As XComment = New XComment("This is a comment") -Dim node As XNode = com -Console.WriteLine(node.NodeType.ToString()) -``` - - This example produces the following output: - -``` -Comment -``` - + contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. + + + +## Examples + The following example creates a comment node and prints its node type. + +```csharp +XComment com = new XComment("This is a comment"); +XNode node = com; +Console.WriteLine(node.NodeType); +``` + +```vb +Dim com As XComment = New XComment("This is a comment") +Dim node As XNode = com +Console.WriteLine(node.NodeType.ToString()) +``` + + This example produces the following output: + +``` +Comment +``` + ]]> @@ -295,34 +295,34 @@ Comment Gets or sets the string value of this comment. A that contains the string value of this comment. - and , you cannot retrieve the contents of a comment by casting it to a string. Instead, you must use this property to retrieve the contents. - - Setting this property will raise the and the events. - - - -## Examples - The following example creates a comment node. It then retrieves the contents of the comment node. - -```csharp -XComment com = new XComment("This is a comment"); -Console.WriteLine(com.Value); -``` - -```vb -Dim com As XComment = New XComment("This is a comment") -Console.WriteLine(com.Value) -``` - - This example produces the following output: - -``` -This is a comment -``` - + and , you cannot retrieve the contents of a comment by casting it to a string. Instead, you must use this property to retrieve the contents. + + Setting this property will raise the and the events. + + + +## Examples + The following example creates a comment node. It then retrieves the contents of the comment node. + +```csharp +XComment com = new XComment("This is a comment"); +Console.WriteLine(com.Value); +``` + +```vb +Dim com As XComment = New XComment("This is a comment") +Console.WriteLine(com.Value) +``` + + This example produces the following output: + +``` +This is a comment +``` + ]]> The is . @@ -370,11 +370,11 @@ This is a comment An into which this method will write. Write this comment to an . - . - + . + ]]> @@ -419,6 +419,7 @@ This is a comment Writes this to the specified . A task that represents the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Xml.Linq/XDocument.xml b/xml/System.Xml.Linq/XDocument.xml index 7f2febda8cb..3496717b8b6 100644 --- a/xml/System.Xml.Linq/XDocument.xml +++ b/xml/System.Xml.Linq/XDocument.xml @@ -40,79 +40,79 @@ Represents an XML document. For the components and usage of an object, see XDocument Class Overview. - , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - - - -## Examples - The following example creates a document, and then adds a comment and an element to it. It then composes another document using the results of a query. - -```csharp -XDocument srcTree = new XDocument( - new XComment("This is a comment"), - new XElement("Root", - new XElement("Child1", "data1"), - new XElement("Child2", "data2"), - new XElement("Child3", "data3"), - new XElement("Child2", "data4"), - new XElement("Info5", "info5"), - new XElement("Info6", "info6"), - new XElement("Info7", "info7"), - new XElement("Info8", "info8") - ) -); - -XDocument doc = new XDocument( - new XComment("This is a comment"), - new XElement("Root", - from el in srcTree.Element("Root").Elements() - where ((string)el).StartsWith("data") - select el - ) -); -Console.WriteLine(doc); -``` - -```vb -Dim srcTree As XDocument = _ - - - - data1 - data2 - data3 - data4 - info5 - info6 - info7 - info8 - -Dim doc As XDocument = _ - - - - <%= From el In srcTree..Elements _ - Where CStr(el).StartsWith("data") _ - Select el %> - -Console.WriteLine(doc) -``` - - This example produces the following output: - -```xml - - - data1 - data2 - data3 - data4 - -``` - + , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + + + +## Examples + The following example creates a document, and then adds a comment and an element to it. It then composes another document using the results of a query. + +```csharp +XDocument srcTree = new XDocument( + new XComment("This is a comment"), + new XElement("Root", + new XElement("Child1", "data1"), + new XElement("Child2", "data2"), + new XElement("Child3", "data3"), + new XElement("Child2", "data4"), + new XElement("Info5", "info5"), + new XElement("Info6", "info6"), + new XElement("Info7", "info7"), + new XElement("Info8", "info8") + ) +); + +XDocument doc = new XDocument( + new XComment("This is a comment"), + new XElement("Root", + from el in srcTree.Element("Root").Elements() + where ((string)el).StartsWith("data") + select el + ) +); +Console.WriteLine(doc); +``` + +```vb +Dim srcTree As XDocument = _ + + + + data1 + data2 + data3 + data4 + info5 + info6 + info7 + info8 + +Dim doc As XDocument = _ + + + + <%= From el In srcTree..Elements _ + Where CStr(el).StartsWith("data") _ + Select el %> + +Console.WriteLine(doc) +``` + + This example produces the following output: + +```xml + + + data1 + data2 + data3 + data4 + +``` + ]]> @@ -132,83 +132,83 @@ Console.WriteLine(doc) Initializes a new instance of the class. - ; to create an with some specified initial content; and to create an as a copy of another object. - - There are not many scenarios that require you to create an . Instead, you can usually create your XML trees with an root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use as your root node. - - For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - - - -## Examples - The following example creates a document, and then adds a comment and an element to it. It then composes another document using the results of a query. - -```csharp -XDocument srcTree = new XDocument( - new XComment("This is a comment"), - new XElement("Root", - new XElement("Child1", "data1"), - new XElement("Child2", "data2"), - new XElement("Child3", "data3"), - new XElement("Child2", "data4"), - new XElement("Info5", "info5"), - new XElement("Info6", "info6"), - new XElement("Info7", "info7"), - new XElement("Info8", "info8") - ) -); - -XDocument doc = new XDocument( - new XComment("This is a comment"), - new XElement("Root", - from el in srcTree.Element("Root").Elements() - where ((string)el).StartsWith("data") - select el - ) -); -Console.WriteLine(doc); -``` - -```vb -Dim srcTree As XDocument = _ - - - - data1 - data2 - data3 - data4 - info5 - info6 - info7 - info8 - -Dim doc As XDocument = _ - - - - <%= From el In srcTree..Elements _ - Where CStr(el).StartsWith("data") _ - Select el %> - -Console.WriteLine(doc) -``` - - This example produces the following output: - -```xml - - - data1 - data2 - data3 - data4 - -``` - + ; to create an with some specified initial content; and to create an as a copy of another object. + + There are not many scenarios that require you to create an . Instead, you can usually create your XML trees with an root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use as your root node. + + For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + + + +## Examples + The following example creates a document, and then adds a comment and an element to it. It then composes another document using the results of a query. + +```csharp +XDocument srcTree = new XDocument( + new XComment("This is a comment"), + new XElement("Root", + new XElement("Child1", "data1"), + new XElement("Child2", "data2"), + new XElement("Child3", "data3"), + new XElement("Child2", "data4"), + new XElement("Info5", "info5"), + new XElement("Info6", "info6"), + new XElement("Info7", "info7"), + new XElement("Info8", "info8") + ) +); + +XDocument doc = new XDocument( + new XComment("This is a comment"), + new XElement("Root", + from el in srcTree.Element("Root").Elements() + where ((string)el).StartsWith("data") + select el + ) +); +Console.WriteLine(doc); +``` + +```vb +Dim srcTree As XDocument = _ + + + + data1 + data2 + data3 + data4 + info5 + info6 + info7 + info8 + +Dim doc As XDocument = _ + + + + <%= From el In srcTree..Elements _ + Where CStr(el).StartsWith("data") _ + Select el %> + +Console.WriteLine(doc) +``` + + This example produces the following output: + +```xml + + + data1 + data2 + data3 + data4 + +``` + ]]> @@ -255,39 +255,39 @@ Console.WriteLine(doc) Initializes a new instance of the class. - . Instead, you can usually create your XML trees with an root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use as your root node. - - For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - - - -## Examples - The following example creates a new document, and then adds a comment and an element to it. - -```csharp -XDocument doc = new XDocument(); -doc.Add(new XComment("This is a comment")); -doc.Add(new XElement("Root", "content")); -Console.WriteLine(doc); -``` - -```vb -Dim doc As XDocument = New XDocument() -doc.Add() -doc.Add(content) -Console.WriteLine(doc) -``` - - This example produces the following output: - -```xml - -content -``` - + . Instead, you can usually create your XML trees with an root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use as your root node. + + For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + + + +## Examples + The following example creates a new document, and then adds a comment and an element to it. + +```csharp +XDocument doc = new XDocument(); +doc.Add(new XComment("This is a comment")); +doc.Add(new XElement("Root", "content")); +Console.WriteLine(doc); +``` + +```vb +Dim doc As XDocument = New XDocument() +doc.Add() +doc.Add(content) +Console.WriteLine(doc) +``` + + This example produces the following output: + +```xml + +content +``` + ]]> @@ -340,81 +340,81 @@ Console.WriteLine(doc) A parameter list of content objects to add to this document. Initializes a new instance of the class with the specified content. - . Instead, you can usually create your XML trees with an root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use as your root node. - - For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - - - -## Examples - The following example creates a document, and then adds a comment and an element to it. It then composes another document using the results of a query. - -```csharp -XDocument srcTree = new XDocument( - new XComment("This is a comment"), - new XElement("Root", - new XElement("Child1", "data1"), - new XElement("Child2", "data2"), - new XElement("Child3", "data3"), - new XElement("Child2", "data4"), - new XElement("Info5", "info5"), - new XElement("Info6", "info6"), - new XElement("Info7", "info7"), - new XElement("Info8", "info8") - ) -); - -XDocument doc = new XDocument( - new XComment("This is a comment"), - new XElement("Root", - from el in srcTree.Element("Root").Elements() - where ((string)el).StartsWith("data") - select el - ) -); -Console.WriteLine(doc); -``` - -```vb -Dim srcTree As XDocument = _ - - - - data1 - data2 - data3 - data4 - info5 - info6 - info7 - info8 - -Dim doc As XDocument = _ - - - - <%= From el In srcTree..Elements _ - Where CStr(el).StartsWith("data") _ - Select el %> - -Console.WriteLine(doc) -``` - - This example produces the following output: - -```xml - - - data1 - data2 - data3 - data4 - -``` - + . Instead, you can usually create your XML trees with an root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use as your root node. + + For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + + + +## Examples + The following example creates a document, and then adds a comment and an element to it. It then composes another document using the results of a query. + +```csharp +XDocument srcTree = new XDocument( + new XComment("This is a comment"), + new XElement("Root", + new XElement("Child1", "data1"), + new XElement("Child2", "data2"), + new XElement("Child3", "data3"), + new XElement("Child2", "data4"), + new XElement("Info5", "info5"), + new XElement("Info6", "info6"), + new XElement("Info7", "info7"), + new XElement("Info8", "info8") + ) +); + +XDocument doc = new XDocument( + new XComment("This is a comment"), + new XElement("Root", + from el in srcTree.Element("Root").Elements() + where ((string)el).StartsWith("data") + select el + ) +); +Console.WriteLine(doc); +``` + +```vb +Dim srcTree As XDocument = _ + + + + data1 + data2 + data3 + data4 + info5 + info6 + info7 + info8 + +Dim doc As XDocument = _ + + + + <%= From el In srcTree..Elements _ + Where CStr(el).StartsWith("data") _ + Select el %> + +Console.WriteLine(doc) +``` + + This example produces the following output: + +```xml + + + data1 + data2 + data3 + data4 + +``` + ]]> @@ -459,13 +459,13 @@ Console.WriteLine(doc) The object that will be copied. Initializes a new instance of the class from an existing object. - . - - This constructor traverses all nodes and attributes in the document specified in the `other` parameter, and creates copies of all nodes as it assembles the newly initialized . - + . + + This constructor traverses all nodes and attributes in the document specified in the `other` parameter, and creates copies of all nodes as it assembles the newly initialized . + ]]> @@ -527,85 +527,85 @@ Console.WriteLine(doc) The content of the document. Initializes a new instance of the class with the specified and content. - . Instead, you can usually create your XML trees with an root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use as your root node. - - For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - - - -## Examples - The following example uses this constructor to create a document. - -```csharp -XDocument srcTree = new XDocument( - new XComment("This is a comment"), - new XElement("Root", - new XElement("Child1", "data1"), - new XElement("Child2", "data2"), - new XElement("Child3", "data3"), - new XElement("Child2", "data4"), - new XElement("Info5", "info5"), - new XElement("Info6", "info6"), - new XElement("Info7", "info7"), - new XElement("Info8", "info8") - ) -); - -XDocument doc = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - new XComment("This is a new comment"), - new XElement("Root", - from el in srcTree.Element("Root").Elements() - where ((string)el).StartsWith("data") - select el - ) -); -doc.Save("Test.xml"); -Console.WriteLine(File.ReadAllText("Test.xml")); -``` - -```vb -Dim srcTree As XDocument = _ - - - - data1 - data2 - data3 - data4 - info5 - info6 - info7 - info8 - -Dim doc As XDocument = _ - - - - <%= From el In srcTree..Elements _ - Where CStr(el).StartsWith("data") _ - Select el %> - -doc.Save("Test.xml") -Console.WriteLine(File.ReadAllText("Test.xml")) -``` - - This example produces the following output: - -```xml - - - - data1 - data2 - data3 - data4 - -``` - + . Instead, you can usually create your XML trees with an root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use as your root node. + + For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + + + +## Examples + The following example uses this constructor to create a document. + +```csharp +XDocument srcTree = new XDocument( + new XComment("This is a comment"), + new XElement("Root", + new XElement("Child1", "data1"), + new XElement("Child2", "data2"), + new XElement("Child3", "data3"), + new XElement("Child2", "data4"), + new XElement("Info5", "info5"), + new XElement("Info6", "info6"), + new XElement("Info7", "info7"), + new XElement("Info8", "info8") + ) +); + +XDocument doc = new XDocument( + new XDeclaration("1.0", "utf-8", "yes"), + new XComment("This is a new comment"), + new XElement("Root", + from el in srcTree.Element("Root").Elements() + where ((string)el).StartsWith("data") + select el + ) +); +doc.Save("Test.xml"); +Console.WriteLine(File.ReadAllText("Test.xml")); +``` + +```vb +Dim srcTree As XDocument = _ + + + + data1 + data2 + data3 + data4 + info5 + info6 + info7 + info8 + +Dim doc As XDocument = _ + + + + <%= From el In srcTree..Elements _ + Where CStr(el).StartsWith("data") _ + Select el %> + +doc.Save("Test.xml") +Console.WriteLine(File.ReadAllText("Test.xml")) +``` + + This example produces the following output: + +```xml + + + + data1 + data2 + data3 + data4 + +``` + ]]> @@ -661,41 +661,41 @@ Console.WriteLine(File.ReadAllText("Test.xml")) Gets or sets the XML declaration for this document. An that contains the XML declaration for this document. - . Another approach for encoding a document is to specify the encoding on an that you pass to LINQ to XML for writing. - - - -## Examples - The following example uses this property to retrieve the XML declaration of a document. - -```csharp -XDocument doc = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - new XComment("This is a comment"), - new XElement("Root", "content") -); - -Console.WriteLine(doc.Declaration); -``` - -```vb -Dim doc As XDocument = _ - - - content - -Console.WriteLine(doc.Declaration) -``` - - This example produces the following output: - -``` - -``` - + . Another approach for encoding a document is to specify the encoding on an that you pass to LINQ to XML for writing. + + + +## Examples + The following example uses this property to retrieve the XML declaration of a document. + +```csharp +XDocument doc = new XDocument( + new XDeclaration("1.0", "utf-8", "yes"), + new XComment("This is a comment"), + new XElement("Root", "content") +); + +Console.WriteLine(doc.Declaration); +``` + +```vb +Dim doc As XDocument = _ + + + content + +Console.WriteLine(doc.Declaration) +``` + + This example produces the following output: + +``` + +``` + ]]> @@ -747,104 +747,104 @@ Console.WriteLine(doc.Declaration) Gets the Document Type Definition (DTD) for this document. A that contains the DTD for this document. - node. When you serialize or save the tree, the DTD will also be serialized. LINQ to XML will expand any entities in the DTD. When you serialize or save the XML tree, the entity references are not saved; instead, the nodes are saved with the entity references replaced by the text of the entity. - - If the DTD contains default attributes, the attributes are created in the XML tree as ordinary attributes. - - By default, LINQ to XML does not validate a document based on its DTD. To validate a document based on a DTD, create an that will validate based on a DTD, and then create an XML tree from the . - - - -## Examples - The following example creates a document that contains an . - - Visual Basic does not support document types within XML literals. However, it is possible to create a document that contains a document type by first creating the document using XML literals, and then creating and adding an node in the appropriate place in the XML tree. - -```csharp -string internalSubset = @" - - -"; - -string target = "xml-stylesheet"; -string data = "href='mystyle.css' title='Compact' type='text/css'"; - -XDocument doc = new XDocument( - new XComment("This is a comment."), - new XProcessingInstruction(target, data), - new XDocumentType("Pubs", null, null, internalSubset), - new XElement("Pubs", - new XElement("Book", - new XElement("Title", "Artifacts of Roman Civilization"), - new XElement("Author", "Moreno, Jordao") - ), - new XElement("Book", - new XElement("Title", "Midieval Tools and Implements"), - new XElement("Author", "Gazit, Inbar") - ) - ), - new XComment("This is another comment.") -); -doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); -Console.WriteLine(doc); - -doc.Save("test.xml"); -``` - -```vb -Dim internalSubset = _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" - -Dim doc As XDocument = _ - - - - - - Artifacts of Roman Civilization - Moreno, Jordao - - - Midieval Tools and Implements - Gazit, Inbar - - - - -doc.Nodes().Skip(1).First().AddAfterSelf(New XDocumentType("Pubs", Nothing, Nothing, internalSubset)) -Console.WriteLine(doc) -``` - - This example produces the following output: - -```xml - - - - - -]> - - - Artifacts of Roman Civilization - Moreno, Jordao - - - Midieval Tools and Implements - Gazit, Inbar - - - -``` - + node. When you serialize or save the tree, the DTD will also be serialized. LINQ to XML will expand any entities in the DTD. When you serialize or save the XML tree, the entity references are not saved; instead, the nodes are saved with the entity references replaced by the text of the entity. + + If the DTD contains default attributes, the attributes are created in the XML tree as ordinary attributes. + + By default, LINQ to XML does not validate a document based on its DTD. To validate a document based on a DTD, create an that will validate based on a DTD, and then create an XML tree from the . + + + +## Examples + The following example creates a document that contains an . + + Visual Basic does not support document types within XML literals. However, it is possible to create a document that contains a document type by first creating the document using XML literals, and then creating and adding an node in the appropriate place in the XML tree. + +```csharp +string internalSubset = @" + + +"; + +string target = "xml-stylesheet"; +string data = "href='mystyle.css' title='Compact' type='text/css'"; + +XDocument doc = new XDocument( + new XComment("This is a comment."), + new XProcessingInstruction(target, data), + new XDocumentType("Pubs", null, null, internalSubset), + new XElement("Pubs", + new XElement("Book", + new XElement("Title", "Artifacts of Roman Civilization"), + new XElement("Author", "Moreno, Jordao") + ), + new XElement("Book", + new XElement("Title", "Midieval Tools and Implements"), + new XElement("Author", "Gazit, Inbar") + ) + ), + new XComment("This is another comment.") +); +doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); +Console.WriteLine(doc); + +doc.Save("test.xml"); +``` + +```vb +Dim internalSubset = _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" + +Dim doc As XDocument = _ + + + + + + Artifacts of Roman Civilization + Moreno, Jordao + + + Midieval Tools and Implements + Gazit, Inbar + + + + +doc.Nodes().Skip(1).First().AddAfterSelf(New XDocumentType("Pubs", Nothing, Nothing, internalSubset)) +Console.WriteLine(doc) +``` + + This example produces the following output: + +```xml + + + + + +]> + + + Artifacts of Roman Civilization + Moreno, Jordao + + + Midieval Tools and Implements + Gazit, Inbar + + + +``` + ]]> @@ -861,13 +861,13 @@ Console.WriteLine(doc) Creates a new from a file specified by a URI, from an , or from an . - from a file, a , or an . - - To create an from a string that contains XML, use . - + from a file, a , or an . + + To create an from a string that contains XML, use . + ]]> @@ -923,19 +923,19 @@ Console.WriteLine(doc) Creates a new instance by using the specified stream. An object that reads the data that is contained in the stream. - overload that takes as a parameter. - - The loading functionality of LINQ to XML is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - If you have to modify , follow these steps: - -1. Create an by calling one of the overloads that take as a parameter. - -2. Pass the to one of the overloads of that takes as a parameter. - + overload that takes as a parameter. + + The loading functionality of LINQ to XML is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + If you have to modify , follow these steps: + +1. Create an by calling one of the overloads that take as a parameter. + +2. Pass the to one of the overloads of that takes as a parameter. + ]]> @@ -987,34 +987,34 @@ Console.WriteLine(doc) Creates a new from a . An that contains the contents of the specified . - . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example creates a document from a . - -```csharp -TextReader tr = new StringReader("Content"); -XDocument doc = XDocument.Load(tr); -Console.WriteLine(doc); -``` - -```vb -Dim tr As TextReader = New StringReader("Content") -Dim doc As XDocument = XDocument.Load(tr) -Console.WriteLine(doc) -``` - - This example produces the following output: - -```xml -Content -``` - + . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example creates a document from a . + +```csharp +TextReader tr = new StringReader("Content"); +XDocument doc = XDocument.Load(tr); +Console.WriteLine(doc); +``` + +```vb +Dim tr As TextReader = New StringReader("Content") +Dim doc As XDocument = XDocument.Load(tr) +Console.WriteLine(doc) +``` + + This example produces the following output: + +```xml +Content +``` + ]]> @@ -1078,72 +1078,72 @@ Console.WriteLine(doc) Creates a new from a file. An that contains the contents of the specified file. - to read the XML into an XML tree. - - Use to create an from a string that contains XML. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example shows how to load an from a file. - - This example uses the following XML document: - - [Sample XML File: Typical Purchase Order (LINQ to XML)](/dotnet/standard/linq/sample-xml-file-typical-purchase-order) - -```csharp -XDocument doc = XDocument.Load("PurchaseOrder.xml"); -Console.WriteLine(doc); -``` - -```vb -Dim doc As XDocument = XDocument.Load("PurchaseOrder.xml") -Console.WriteLine(doc) -``` - - This example produces the following output: - -``` - -
- Ellen Adams - 123 Maple Street - Mill Valley - CA - 10999 - USA -
-
- Tai Yee - 8 Oak Avenue - Old Town - PA - 95819 - USA -
- Please leave packages in shed by driveway. - - - Lawnmower - 1 - 148.95 - Confirm this is electric - - - Baby Monitor - 2 - 39.98 - 1999-05-21 - - -
-``` - + to read the XML into an XML tree. + + Use to create an from a string that contains XML. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example shows how to load an from a file. + + This example uses the following XML document: + + [Sample XML File: Typical Purchase Order (LINQ to XML)](/dotnet/standard/linq/sample-xml-file-typical-purchase-order) + +```csharp +XDocument doc = XDocument.Load("PurchaseOrder.xml"); +Console.WriteLine(doc); +``` + +```vb +Dim doc As XDocument = XDocument.Load("PurchaseOrder.xml") +Console.WriteLine(doc) +``` + + This example produces the following output: + +``` + +
+ Ellen Adams + 123 Maple Street + Mill Valley + CA + 10999 + USA +
+
+ Tai Yee + 8 Oak Avenue + Old Town + PA + 95819 + USA +
+ Please leave packages in shed by driveway. + + + Lawnmower + 1 + 148.95 + Confirm this is electric + + + Baby Monitor + 2 + 39.98 + 1999-05-21 + + +
+``` + ]]>
@@ -1200,66 +1200,66 @@ Console.WriteLine(doc) Creates a new from an . An that contains the contents of the specified . - from a DOM document, and then use the to create an . - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example creates a DOM document, creates an from the DOM document, creates an using the . - -```csharp -// Create a DOM document with some content. -XmlDocument doc = new XmlDocument(); -XmlElement child = doc.CreateElement("Child"); -child.InnerText = "child contents"; -XmlElement root = doc.CreateElement("Root"); -root.AppendChild(child); -doc.AppendChild(root); - -// create a reader and move to the content -using (XmlNodeReader nodeReader = new XmlNodeReader(doc)) { - // the reader must be in the Interactive state in order to - // create a LINQ to XML tree from it. - nodeReader.MoveToContent(); - - XDocument xRoot = XDocument.Load(nodeReader); - Console.WriteLine(xRoot); -} -``` - -```vb -' Create a DOM document with some content. -Dim doc As XmlDocument = New XmlDocument() -Dim child As XmlElement = doc.CreateElement("Child") -child.InnerText = "child contents" -Dim root As XmlElement = doc.CreateElement("Root") -root.AppendChild(child) -doc.AppendChild(root) - -' create a reader and move to the content -Using nodeReader = New XmlNodeReader(doc) - ' the reader must be in the Interactive state in order to - ' create a LINQ to XML tree from it. - nodeReader.MoveToContent() - - Dim xRoot As XDocument = XDocument.Load(nodeReader) - Console.WriteLine(xRoot) -End Using -``` - - This example produces the following output: - -```xml - - child contents - -``` - + from a DOM document, and then use the to create an . + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example creates a DOM document, creates an from the DOM document, creates an using the . + +```csharp +// Create a DOM document with some content. +XmlDocument doc = new XmlDocument(); +XmlElement child = doc.CreateElement("Child"); +child.InnerText = "child contents"; +XmlElement root = doc.CreateElement("Root"); +root.AppendChild(child); +doc.AppendChild(root); + +// create a reader and move to the content +using (XmlNodeReader nodeReader = new XmlNodeReader(doc)) { + // the reader must be in the Interactive state in order to + // create a LINQ to XML tree from it. + nodeReader.MoveToContent(); + + XDocument xRoot = XDocument.Load(nodeReader); + Console.WriteLine(xRoot); +} +``` + +```vb +' Create a DOM document with some content. +Dim doc As XmlDocument = New XmlDocument() +Dim child As XmlElement = doc.CreateElement("Child") +child.InnerText = "child contents" +Dim root As XmlElement = doc.CreateElement("Root") +root.AppendChild(child) +doc.AppendChild(root) + +' create a reader and move to the content +Using nodeReader = New XmlNodeReader(doc) + ' the reader must be in the Interactive state in order to + ' create a LINQ to XML tree from it. + nodeReader.MoveToContent() + + Dim xRoot As XDocument = XDocument.Load(nodeReader) + Console.WriteLine(xRoot) +End Using +``` + + This example produces the following output: + +```xml + + child contents + +``` + ]]> @@ -1311,17 +1311,17 @@ End Using Creates a new instance by using the specified stream, optionally preserving white space, setting the base URI, and retaining line information. An object that reads the data that is contained in the stream. - . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - If you have to modify , follow these steps: - -1. Create an by calling one of the overloads that takes as a parameter. - -2. Pass the to one of the overloads of that takes as a parameter. - + . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + If you have to modify , follow these steps: + +1. Create an by calling one of the overloads that takes as a parameter. + +2. Pass the to one of the overloads of that takes as a parameter. + ]]>
@@ -1369,93 +1369,93 @@ End Using Creates a new from a , optionally preserving white space, setting the base URI, and retaining line information. An that contains the XML that was read from the specified . - flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. - - If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. - - If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - Use to create an from a string that contains XML. - - Setting is not valid when loading from a . - - There is a performance penalty if you set the flag. - - The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example creates a document from a . - -```csharp -TextReader sr; -int whiteSpaceNodes; - -sr = new StringReader(" "); -XDocument xmlTree1 = XDocument.Load(sr, LoadOptions.None); -sr.Close(); -whiteSpaceNodes = xmlTree1 - .Element("Root") - .DescendantNodesAndSelf() - .OfType() - .Where(tNode => tNode.ToString().Trim().Length == 0) - .Count(); -Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes); - -sr = new StringReader(" "); -XDocument xmlTree2 = XDocument.Load(sr, LoadOptions.PreserveWhitespace); -sr.Close(); -whiteSpaceNodes = xmlTree2 - .Element("Root") - .DescendantNodesAndSelf() - .OfType() - .Where(tNode => tNode.ToString().Trim().Length == 0) - .Count(); -Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes); -``` - -```vb -Dim sr As TextReader -Dim whiteSpaceNodes As Integer - -sr = New StringReader(" ") -Dim xmlTree1 As XDocument = XDocument.Load(sr, LoadOptions.None) -sr.Close() -whiteSpaceNodes = xmlTree1 _ - .Element("Root") _ - .DescendantNodesAndSelf() _ - .OfType(Of XText)() _ - .Where(Function(ByVal tNode As XNode) tNode. _ - ToString().Trim().Length = 0).Count() -Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes) - -sr = New StringReader(" ") -Dim xmlTree2 As XDocument = XDocument.Load(sr, LoadOptions.PreserveWhitespace) -sr.Close() -whiteSpaceNodes = xmlTree2 _ - .Element("Root") _ - .DescendantNodesAndSelf() _ - .OfType(Of XText)() _ - .Where(Function(ByVal tNode As XNode) tNode. _ - ToString().Trim().Length = 0).Count() -Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes) -``` - - This example produces the following output: - -``` -Count of white space nodes (not preserving whitespace): 0 -Count of white space nodes (preserving whitespace): 3 -``` - + flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. + + If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. + + If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + Use to create an from a string that contains XML. + + Setting is not valid when loading from a . + + There is a performance penalty if you set the flag. + + The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example creates a document from a . + +```csharp +TextReader sr; +int whiteSpaceNodes; + +sr = new StringReader(" "); +XDocument xmlTree1 = XDocument.Load(sr, LoadOptions.None); +sr.Close(); +whiteSpaceNodes = xmlTree1 + .Element("Root") + .DescendantNodesAndSelf() + .OfType() + .Where(tNode => tNode.ToString().Trim().Length == 0) + .Count(); +Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes); + +sr = new StringReader(" "); +XDocument xmlTree2 = XDocument.Load(sr, LoadOptions.PreserveWhitespace); +sr.Close(); +whiteSpaceNodes = xmlTree2 + .Element("Root") + .DescendantNodesAndSelf() + .OfType() + .Where(tNode => tNode.ToString().Trim().Length == 0) + .Count(); +Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes); +``` + +```vb +Dim sr As TextReader +Dim whiteSpaceNodes As Integer + +sr = New StringReader(" ") +Dim xmlTree1 As XDocument = XDocument.Load(sr, LoadOptions.None) +sr.Close() +whiteSpaceNodes = xmlTree1 _ + .Element("Root") _ + .DescendantNodesAndSelf() _ + .OfType(Of XText)() _ + .Where(Function(ByVal tNode As XNode) tNode. _ + ToString().Trim().Length = 0).Count() +Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes) + +sr = New StringReader(" ") +Dim xmlTree2 As XDocument = XDocument.Load(sr, LoadOptions.PreserveWhitespace) +sr.Close() +whiteSpaceNodes = xmlTree2 _ + .Element("Root") _ + .DescendantNodesAndSelf() _ + .OfType(Of XText)() _ + .Where(Function(ByVal tNode As XNode) tNode. _ + ToString().Trim().Length = 0).Count() +Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes) +``` + + This example produces the following output: + +``` +Count of white space nodes (not preserving whitespace): 0 +Count of white space nodes (preserving whitespace): 3 +``` + ]]> @@ -1515,57 +1515,57 @@ Count of white space nodes (preserving whitespace): 3 Creates a new from a file, optionally preserving white space, setting the base URI, and retaining line information. An that contains the contents of the specified file. - flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. - - If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. - - If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - Use to create an from a string that contains XML. - - There is a performance penalty if you set the and the flags. - - The base URI and the line information are accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the base URI and line information may become meaningless. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example shows how to load an from a file. - - This example uses the following XML document: - - [Sample XML File: Typical Purchase Order (LINQ to XML)](/dotnet/standard/linq/sample-xml-file-typical-purchase-order) - -```csharp -XDocument doc1 = XDocument.Load("PurchaseOrder.xml", LoadOptions.None); -Console.WriteLine("nodes if not preserving whitespace: {0}", doc1.DescendantNodes().Count()); - -XDocument doc2 = XDocument.Load("PurchaseOrder.xml", LoadOptions.PreserveWhitespace); -Console.WriteLine("nodes if preserving whitespace: {0}", doc2.DescendantNodes().Count()); -``` - -```vb -Dim doc1 As XDocument = XDocument.Load("PurchaseOrder.xml", LoadOptions.None) -Console.WriteLine("nodes if not preserving whitespace: {0}", doc1.DescendantNodes().Count()) - -Dim doc2 As XDocument = XDocument.Load("PurchaseOrder.xml", LoadOptions.PreserveWhitespace) -Console.WriteLine("nodes if preserving whitespace: {0}", doc2.DescendantNodes().Count()) -``` - - This example produces the following output: - -``` -nodes if not preserving whitespace: 48 -nodes if preserving whitespace: 82 -``` - + flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. + + If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. + + If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + Use to create an from a string that contains XML. + + There is a performance penalty if you set the and the flags. + + The base URI and the line information are accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the base URI and line information may become meaningless. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example shows how to load an from a file. + + This example uses the following XML document: + + [Sample XML File: Typical Purchase Order (LINQ to XML)](/dotnet/standard/linq/sample-xml-file-typical-purchase-order) + +```csharp +XDocument doc1 = XDocument.Load("PurchaseOrder.xml", LoadOptions.None); +Console.WriteLine("nodes if not preserving whitespace: {0}", doc1.DescendantNodes().Count()); + +XDocument doc2 = XDocument.Load("PurchaseOrder.xml", LoadOptions.PreserveWhitespace); +Console.WriteLine("nodes if preserving whitespace: {0}", doc2.DescendantNodes().Count()); +``` + +```vb +Dim doc1 As XDocument = XDocument.Load("PurchaseOrder.xml", LoadOptions.None) +Console.WriteLine("nodes if not preserving whitespace: {0}", doc1.DescendantNodes().Count()) + +Dim doc2 As XDocument = XDocument.Load("PurchaseOrder.xml", LoadOptions.PreserveWhitespace) +Console.WriteLine("nodes if preserving whitespace: {0}", doc2.DescendantNodes().Count()) +``` + + This example produces the following output: + +``` +nodes if not preserving whitespace: 48 +nodes if preserving whitespace: 82 +``` + ]]> @@ -1618,105 +1618,105 @@ nodes if preserving whitespace: 82 Loads an from an , optionally setting the base URI, and retaining line information. An that contains the XML that was read from the specified . - from a DOM document, and then using the to create an , this method can be used to create a copy of a DOM document in a LINQ to XML tree. - - Use to create an from a string that contains XML. - - Setting is not valid when loading from a . The will be configured to either read whitespace or not. The LINQ to XML tree will be populated with the whitespace nodes that the reader surfaces. This will be the behavior regardless of whether is set or not. - - The may have a valid base URI or not. If you set , the base URI will be set in the XML tree from the base URI that is reported by the . - - The may have a valid line information or not. If you set , the line information will be set in the XML tree from the line information that is reported by the . - - There is a performance penalty if you set the flag. - - The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example loads the line information that it loads from the . It then prints the line information. - -```csharp -string markup = -@" - - - -"; - -// Create a reader and move to the content. -using (XmlReader nodeReader = XmlReader.Create(new StringReader(markup))) -{ - // the reader must be in the Interactive state in order to - // Create a LINQ to XML tree from it. - nodeReader.MoveToContent(); - - XDocument xRoot = XDocument.Load(nodeReader, LoadOptions.SetLineInfo); - Console.WriteLine("{0}{1}{2}", - "Element Name".PadRight(20), - "Line".PadRight(5), - "Position"); - Console.WriteLine("{0}{1}{2}", - "------------".PadRight(20), - "----".PadRight(5), - "--------"); - foreach (XElement e in xRoot.Elements("Root").DescendantsAndSelf()) - Console.WriteLine("{0}{1}{2}", - ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), - ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), - ((IXmlLineInfo)e).LinePosition); -} -``` - -```vb -Dim markup As String = _ - "" & Environment.NewLine & _ - " " & Environment.NewLine & _ - " " & Environment.NewLine & _ - " " & Environment.NewLine & _ - "" - -' Create a reader and move to the content. -Using nodeReader As XmlReader = XmlReader.Create(New StringReader(markup)) - - ' The reader must be in the Interactive state in order to - ' create a LINQ to XML tree from it. - nodeReader.MoveToContent() - - Dim xRoot As XDocument = XDocument.Load(nodeReader, LoadOptions.SetLineInfo) - Console.WriteLine("{0}{1}{2}", _ - "Element Name".PadRight(20), _ - "Line".PadRight(5), _ - "Position") - Console.WriteLine("{0}{1}{2}", _ - "------------".PadRight(20), _ - "----".PadRight(5), _ - "--------") - For Each e As XElement In xRoot.Elements("Root").DescendantsAndSelf() - Console.WriteLine("{0}{1}{2}", _ - ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString()).PadRight(20), _ - (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _ - (DirectCast(e, IXmlLineInfo)).LinePosition) - Next -End Using -``` - - This example produces the following output: - -``` -Element Name Line Position ------------- ---- -------- -Root 1 2 - Child 2 6 - GrandChild 3 10 -``` - + from a DOM document, and then using the to create an , this method can be used to create a copy of a DOM document in a LINQ to XML tree. + + Use to create an from a string that contains XML. + + Setting is not valid when loading from a . The will be configured to either read whitespace or not. The LINQ to XML tree will be populated with the whitespace nodes that the reader surfaces. This will be the behavior regardless of whether is set or not. + + The may have a valid base URI or not. If you set , the base URI will be set in the XML tree from the base URI that is reported by the . + + The may have a valid line information or not. If you set , the line information will be set in the XML tree from the line information that is reported by the . + + There is a performance penalty if you set the flag. + + The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example loads the line information that it loads from the . It then prints the line information. + +```csharp +string markup = +@" + + + +"; + +// Create a reader and move to the content. +using (XmlReader nodeReader = XmlReader.Create(new StringReader(markup))) +{ + // the reader must be in the Interactive state in order to + // Create a LINQ to XML tree from it. + nodeReader.MoveToContent(); + + XDocument xRoot = XDocument.Load(nodeReader, LoadOptions.SetLineInfo); + Console.WriteLine("{0}{1}{2}", + "Element Name".PadRight(20), + "Line".PadRight(5), + "Position"); + Console.WriteLine("{0}{1}{2}", + "------------".PadRight(20), + "----".PadRight(5), + "--------"); + foreach (XElement e in xRoot.Elements("Root").DescendantsAndSelf()) + Console.WriteLine("{0}{1}{2}", + ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), + ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), + ((IXmlLineInfo)e).LinePosition); +} +``` + +```vb +Dim markup As String = _ + "" & Environment.NewLine & _ + " " & Environment.NewLine & _ + " " & Environment.NewLine & _ + " " & Environment.NewLine & _ + "" + +' Create a reader and move to the content. +Using nodeReader As XmlReader = XmlReader.Create(New StringReader(markup)) + + ' The reader must be in the Interactive state in order to + ' create a LINQ to XML tree from it. + nodeReader.MoveToContent() + + Dim xRoot As XDocument = XDocument.Load(nodeReader, LoadOptions.SetLineInfo) + Console.WriteLine("{0}{1}{2}", _ + "Element Name".PadRight(20), _ + "Line".PadRight(5), _ + "Position") + Console.WriteLine("{0}{1}{2}", _ + "------------".PadRight(20), _ + "----".PadRight(5), _ + "--------") + For Each e As XElement In xRoot.Elements("Root").DescendantsAndSelf() + Console.WriteLine("{0}{1}{2}", _ + ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString()).PadRight(20), _ + (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _ + (DirectCast(e, IXmlLineInfo)).LinePosition) + Next +End Using +``` + + This example produces the following output: + +``` +Element Name Line Position +------------ ---- -------- +Root 1 2 + Child 2 6 + GrandChild 3 10 +``` + ]]> @@ -1775,6 +1775,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task.
@@ -1826,6 +1827,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task.
@@ -1867,6 +1869,7 @@ This method stores in the task it returns all non-usage exceptions that the meth Creates a new containing the contents of the specified . A new XDocument containing the contents of the specified . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -1906,39 +1909,39 @@ This method stores in the task it returns all non-usage exceptions that the meth Gets the node type for this node. The node type. For objects, this value is . - contain a property, you can write code that operates on collections of objects where the type of each is a subclass of . Your code can then test for the node type of each object in the collection. - - - -## Examples - The following example shows the use of this property. - -```csharp -// Note that this property uses XmlNodeType, which is in the System.Xml namespace. -XDocument xmlTree = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - new XElement("Root", "content") -); -Console.WriteLine(xmlTree.NodeType); -``` - -```vb -' Note that this property uses XmlNodeType, which is in the System.Xml namespace. -Dim xmlTree As XDocument = _ - - content -Console.WriteLine("{0}", xmlTree.NodeType) -``` - - This example produces the following output: - -``` -Document -``` - + contain a property, you can write code that operates on collections of objects where the type of each is a subclass of . Your code can then test for the node type of each object in the collection. + + + +## Examples + The following example shows the use of this property. + +```csharp +// Note that this property uses XmlNodeType, which is in the System.Xml namespace. +XDocument xmlTree = new XDocument( + new XDeclaration("1.0", "utf-8", "yes"), + new XElement("Root", "content") +); +Console.WriteLine(xmlTree.NodeType); +``` + +```vb +' Note that this property uses XmlNodeType, which is in the System.Xml namespace. +Dim xmlTree As XDocument = _ + + content +Console.WriteLine("{0}", xmlTree.NodeType) +``` + + This example produces the following output: + +``` +Document +``` + ]]> @@ -1955,48 +1958,48 @@ Document Creates a new from a string, optionally preserving white space, setting the base URI, and retaining line information. - . - -```csharp -string str = -@" - - - Content -"; -XDocument doc = XDocument.Parse(str); -Console.WriteLine(doc); -``` - -```vb -Dim str As String = _ - "" & _ - "" & _ - "" & _ - " Content" & _ - "" - -Dim doc As XDocument = XDocument.Parse(str) -Console.WriteLine(doc) -``` - - This example produces the following output: - -```xml - - - Content - -``` - + . + +```csharp +string str = +@" + + + Content +"; +XDocument doc = XDocument.Parse(str); +Console.WriteLine(doc); +``` + +```vb +Dim str As String = _ + "" & _ + "" & _ + "" & _ + " Content" & _ + "" + +Dim doc As XDocument = XDocument.Parse(str) +Console.WriteLine(doc) +``` + + This example produces the following output: + +```xml + + + Content + +``` + ]]> @@ -2053,52 +2056,52 @@ Console.WriteLine(doc) Creates a new from a string. An populated from the string that contains XML. - that takes as a parameter. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example creates a string that contains XML. It then parses the string into an . - -```csharp -string str = -@" - - - Content -"; -XDocument doc = XDocument.Parse(str); -Console.WriteLine(doc); -``` - -```vb -Dim str As String = _ - "" & _ - "" & _ - "" & _ - " Content" & _ - "" - -Dim doc As XDocument = XDocument.Parse(str) -Console.WriteLine(doc) -``` - - This example produces the following output: - -```xml - - - Content - -``` - + that takes as a parameter. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example creates a string that contains XML. It then parses the string into an . + +```csharp +string str = +@" + + + Content +"; +XDocument doc = XDocument.Parse(str); +Console.WriteLine(doc); +``` + +```vb +Dim str As String = _ + "" & _ + "" & _ + "" & _ + " Content" & _ + "" + +Dim doc As XDocument = XDocument.Parse(str) +Console.WriteLine(doc) +``` + + This example produces the following output: + +```xml + + + Content + +``` + ]]> @@ -2151,64 +2154,64 @@ Console.WriteLine(doc) Creates a new from a string, optionally preserving white space, setting the base URI, and retaining line information. An populated from the string that contains XML. - flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. - - If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. - - If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - Setting is not valid when parsing from a . - - There is a performance penalty if you set the flag. - - The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example parses a string into an . - -```csharp -string str = -@" - - - Content -"; -XDocument doc1 = XDocument.Parse(str, LoadOptions.PreserveWhitespace); -Console.WriteLine("nodes when preserving whitespace: {0}", doc1.DescendantNodes().Count()); -XDocument doc2 = XDocument.Parse(str, LoadOptions.None); -Console.WriteLine("nodes when not preserving whitespace: {0}", doc2.DescendantNodes().Count()); -``` - -```vb -Dim str As String = _ -"" & Environment.NewLine & _ -"" & Environment.NewLine & _ -"" & Environment.NewLine & _ -" Content" & Environment.NewLine & _ -"" - -Dim doc1 As XDocument = XDocument.Parse(str, LoadOptions.PreserveWhitespace) -Console.WriteLine("nodes when preserving whitespace: {0}", doc1.DescendantNodes().Count()) -Dim doc2 As XDocument = XDocument.Parse(str, LoadOptions.None) -Console.WriteLine("nodes when not preserving whitespace: {0}", doc2.DescendantNodes().Count()) -``` - - This example produces the following output: - -``` -nodes when preserving whitespace: 8 -nodes when not preserving whitespace: 4 -``` - + flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. + + If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. + + If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + Setting is not valid when parsing from a . + + There is a performance penalty if you set the flag. + + The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example parses a string into an . + +```csharp +string str = +@" + + + Content +"; +XDocument doc1 = XDocument.Parse(str, LoadOptions.PreserveWhitespace); +Console.WriteLine("nodes when preserving whitespace: {0}", doc1.DescendantNodes().Count()); +XDocument doc2 = XDocument.Parse(str, LoadOptions.None); +Console.WriteLine("nodes when not preserving whitespace: {0}", doc2.DescendantNodes().Count()); +``` + +```vb +Dim str As String = _ +"" & Environment.NewLine & _ +"" & Environment.NewLine & _ +"" & Environment.NewLine & _ +" Content" & Environment.NewLine & _ +"" + +Dim doc1 As XDocument = XDocument.Parse(str, LoadOptions.PreserveWhitespace) +Console.WriteLine("nodes when preserving whitespace: {0}", doc1.DescendantNodes().Count()) +Dim doc2 As XDocument = XDocument.Parse(str, LoadOptions.None) +Console.WriteLine("nodes when not preserving whitespace: {0}", doc2.DescendantNodes().Count()) +``` + + This example produces the following output: + +``` +nodes when preserving whitespace: 8 +nodes when not preserving whitespace: 4 +``` + ]]> @@ -2262,59 +2265,59 @@ nodes when not preserving whitespace: 4 Gets the root element of the XML Tree for this document. The root of the XML tree. - . See [Query an XDocument vs. query an XElement](/dotnet/standard/linq/query-xdocument-vs-query-xelement) for more details. - - - -## Examples - The following example uses this property to get the root element of a document. - -```csharp -XDocument doc = new XDocument( - new XComment("This is a comment."), - new XElement("Pubs", - new XElement("Book", - new XElement("Title", "Artifacts of Roman Civilization"), - new XElement("Author", "Moreno, Jordao") - ), - new XElement("Book", - new XElement("Title", "Midieval Tools and Implements"), - new XElement("Author", "Gazit, Inbar") - ) - ), - new XComment("This is another comment.") -); -Console.WriteLine(doc.Root.Name.ToString()); -``` - -```vb -Dim doc As XDocument = _ - - - - - Artifacts of Roman Civilization - Moreno, Jordao - - - Midieval Tools and Implements - Gazit, Inbar - - - - -Console.WriteLine(doc.Root.Name.ToString()) -``` - - This example produces the following output: - -``` -Pubs -``` - + . See [Query an XDocument vs. query an XElement](/dotnet/standard/linq/query-xdocument-vs-query-xelement) for more details. + + + +## Examples + The following example uses this property to get the root element of a document. + +```csharp +XDocument doc = new XDocument( + new XComment("This is a comment."), + new XElement("Pubs", + new XElement("Book", + new XElement("Title", "Artifacts of Roman Civilization"), + new XElement("Author", "Moreno, Jordao") + ), + new XElement("Book", + new XElement("Title", "Midieval Tools and Implements"), + new XElement("Author", "Gazit, Inbar") + ) + ), + new XComment("This is another comment.") +); +Console.WriteLine(doc.Root.Name.ToString()); +``` + +```vb +Dim doc As XDocument = _ + + + + + Artifacts of Roman Civilization + Moreno, Jordao + + + Midieval Tools and Implements + Gazit, Inbar + + + + +Console.WriteLine(doc.Root.Name.ToString()) +``` + + This example produces the following output: + +``` +Pubs +``` + ]]> LINQ to XML overview @@ -2376,15 +2379,15 @@ Pubs The stream to output this to. Outputs this to the specified . - that takes as a parameter. Use the option to save unindented XML. This will cause the writer to write all white spaces exactly as represented in the XML tree. - - Use option if you want to remove duplicate namespace declarations. - + that takes as a parameter. Use the option to save unindented XML. This will cause the writer to write all white spaces exactly as represented in the XML tree. + + Use option if you want to remove duplicate namespace declarations. + ]]> @@ -2429,52 +2432,52 @@ Pubs A that the will be written to. Serialize this to a . - that takes as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - - -## Examples - The following example creates an , saves the document to a , and then prints the string to the console. - -```csharp -StringBuilder sb = new StringBuilder(); - -XDocument doc = new XDocument( - new XElement("Root", - new XElement("Child", "content") - ) -); -TextWriter tr = new StringWriter(sb); -doc.Save(tr); -Console.WriteLine(sb.ToString()); -``` - -```vb -Dim sb As StringBuilder = New StringBuilder() - -Dim doc As XDocument = _ - - content - -Dim tr As TextWriter = New StringWriter(sb) -doc.Save(tr) -Console.WriteLine(sb.ToString()) -``` - - This example produces the following output: - -```xml - - - content - -``` - + that takes as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + + +## Examples + The following example creates an , saves the document to a , and then prints the string to the console. + +```csharp +StringBuilder sb = new StringBuilder(); + +XDocument doc = new XDocument( + new XElement("Root", + new XElement("Child", "content") + ) +); +TextWriter tr = new StringWriter(sb); +doc.Save(tr); +Console.WriteLine(sb.ToString()); +``` + +```vb +Dim sb As StringBuilder = New StringBuilder() + +Dim doc As XDocument = _ + + content + +Dim tr As TextWriter = New StringWriter(sb) +doc.Save(tr) +Console.WriteLine(sb.ToString()) +``` + + This example produces the following output: + +```xml + + + content + +``` + ]]> @@ -2522,46 +2525,46 @@ Console.WriteLine(sb.ToString()) A string that contains the name of the file. Serialize this to a file, overwriting an existing file, if it exists. - that takes as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - - -## Examples - The following example creates an , saves the document to a file, and then prints the file to the console. - -```csharp -XDocument doc = new XDocument( - new XElement("Root", - new XElement("Child", "content") - ) -); -doc.Save("Root.xml"); -Console.WriteLine(File.ReadAllText("Root.xml")); -``` - -```vb -Dim doc As XDocument = _ - - content - -doc.Save("Root.xml") -Console.WriteLine(File.ReadAllText("Root.xml")) -``` - - This example produces the following output: - -```xml - - - content - -``` - + that takes as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + + +## Examples + The following example creates an , saves the document to a file, and then prints the file to the console. + +```csharp +XDocument doc = new XDocument( + new XElement("Root", + new XElement("Child", "content") + ) +); +doc.Save("Root.xml"); +Console.WriteLine(File.ReadAllText("Root.xml")); +``` + +```vb +Dim doc As XDocument = _ + + content + +doc.Save("Root.xml") +Console.WriteLine(File.ReadAllText("Root.xml")) +``` + + This example produces the following output: + +```xml + + + content + +``` + ]]> @@ -2611,52 +2614,52 @@ Console.WriteLine(File.ReadAllText("Root.xml")) A that the will be written to. Serialize this to an . - to an . - -```csharp -StringBuilder sb = new StringBuilder(); -XmlWriterSettings xws = new XmlWriterSettings(); -xws.OmitXmlDeclaration = true; -xws.Indent = true; - -using (XmlWriter xw = XmlWriter.Create(sb, xws)) { - XDocument doc = new XDocument( - new XElement("Child", - new XElement("GrandChild", "some content") - ) - ); - doc.Save(xw); -} - -Console.WriteLine(sb.ToString()); -``` - -```vb -Dim sb As StringBuilder = New StringBuilder() -Dim xws As XmlWriterSettings = New XmlWriterSettings() -xws.OmitXmlDeclaration = True -xws.Indent = True - -Using xw = XmlWriter.Create(sb, xws) - Dim doc As XDocument = New XDocument(some content) - doc.Save(xw) - -End Using - -Console.WriteLine(sb.ToString()) -``` - - This example produces the following output: - -```xml - - some content - -``` - + to an . + +```csharp +StringBuilder sb = new StringBuilder(); +XmlWriterSettings xws = new XmlWriterSettings(); +xws.OmitXmlDeclaration = true; +xws.Indent = true; + +using (XmlWriter xw = XmlWriter.Create(sb, xws)) { + XDocument doc = new XDocument( + new XElement("Child", + new XElement("GrandChild", "some content") + ) + ); + doc.Save(xw); +} + +Console.WriteLine(sb.ToString()); +``` + +```vb +Dim sb As StringBuilder = New StringBuilder() +Dim xws As XmlWriterSettings = New XmlWriterSettings() +xws.OmitXmlDeclaration = True +xws.Indent = True + +Using xw = XmlWriter.Create(sb, xws) + Dim doc As XDocument = New XDocument(some content) + doc.Save(xw) + +End Using + +Console.WriteLine(sb.ToString()) +``` + + This example produces the following output: + +```xml + + some content + +``` + ]]> @@ -2707,15 +2710,15 @@ Console.WriteLine(sb.ToString()) A that specifies formatting behavior. Outputs this to the specified , optionally specifying formatting behavior. - . This option will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. - - If you want to save unindented XML, specify the flag for `options`. This will cause the writer to write all white spaces exactly as represented in the XML tree. - - Use option if you want to remove duplicate namespace declarations. - + . This option will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. + + If you want to save unindented XML, specify the flag for `options`. This will cause the writer to write all white spaces exactly as represented in the XML tree. + + Use option if you want to remove duplicate namespace declarations. + ]]> @@ -2762,69 +2765,69 @@ Console.WriteLine(sb.ToString()) A that specifies formatting behavior. Serialize this to a , optionally disabling formatting. - flag for `options`. This will cause the writer to write all white space exactly as represented in the XML tree. - - If you want to save indented XML, do not specify the flag for `options`. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the methods that do not take `options` as a parameter. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - - -## Examples - The following example shows two uses of this method. The first use serializes the with formatting. The second preserves white space. Because the document has no white space in it as constructed, preserving white space outputs the XML without any indenting. - -```csharp -XDocument doc = new XDocument( - new XElement("Root", - new XElement("Child", "content") - ) -); -StringBuilder sb1 = new StringBuilder(); -using (StringWriter sr1 = new StringWriter(sb1)) { - doc.Save(sr1, SaveOptions.None); - Console.WriteLine(sb1.ToString()); -} - -StringBuilder sb2 = new StringBuilder(); -using (StringWriter sr2 = new StringWriter(sb2)) { - doc.Save(sr2, SaveOptions.DisableFormatting); - Console.WriteLine(sb2.ToString()); -} -``` - -```vb -Dim doc As XDocument = _ - - content - -Dim sb1 As StringBuilder = New StringBuilder() - -Using sr1 = New StringWriter(sb1) - doc.Save(sr1, SaveOptions.None) - Console.WriteLine(sb1.ToString()) -End Using - -Dim sb2 As StringBuilder = New StringBuilder() - -Using sr2 = New StringWriter(sb2) - doc.Save(sr2, SaveOptions.DisableFormatting) - Console.WriteLine(sb2.ToString()) -End Using -``` - - This example produces the following output: - -``` - - - content - -content -``` - + flag for `options`. This will cause the writer to write all white space exactly as represented in the XML tree. + + If you want to save indented XML, do not specify the flag for `options`. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the methods that do not take `options` as a parameter. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + + +## Examples + The following example shows two uses of this method. The first use serializes the with formatting. The second preserves white space. Because the document has no white space in it as constructed, preserving white space outputs the XML without any indenting. + +```csharp +XDocument doc = new XDocument( + new XElement("Root", + new XElement("Child", "content") + ) +); +StringBuilder sb1 = new StringBuilder(); +using (StringWriter sr1 = new StringWriter(sb1)) { + doc.Save(sr1, SaveOptions.None); + Console.WriteLine(sb1.ToString()); +} + +StringBuilder sb2 = new StringBuilder(); +using (StringWriter sr2 = new StringWriter(sb2)) { + doc.Save(sr2, SaveOptions.DisableFormatting); + Console.WriteLine(sb2.ToString()); +} +``` + +```vb +Dim doc As XDocument = _ + + content + +Dim sb1 As StringBuilder = New StringBuilder() + +Using sr1 = New StringWriter(sb1) + doc.Save(sr1, SaveOptions.None) + Console.WriteLine(sb1.ToString()) +End Using + +Dim sb2 As StringBuilder = New StringBuilder() + +Using sr2 = New StringWriter(sb2) + doc.Save(sr2, SaveOptions.DisableFormatting) + Console.WriteLine(sb2.ToString()) +End Using +``` + + This example produces the following output: + +``` + + + content + +content +``` + ]]> @@ -2874,53 +2877,53 @@ End Using A that specifies formatting behavior. Serialize this to a file, optionally disabling formatting. - flag for `options`. This will cause the writer to write all white space exactly as represented in the XML tree. - - If you want to save indented XML, do not specify the flag for `options`. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the methods that do not take `options` as a parameter. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - - -## Examples - The following example shows two uses of this method. The first use preserves white space. The second one serializes the with indenting. - -```csharp -XDocument doc = new XDocument( - new XElement("Root", - new XElement("Child", "content") - ) -); -doc.Save("Root1.xml", SaveOptions.DisableFormatting); -Console.WriteLine(File.ReadAllText("Root1.xml")); -doc.Save("Root2.xml", SaveOptions.None); -Console.WriteLine(File.ReadAllText("Root2.xml")); -``` - -```vb -Dim doc As XDocument = _ - - content - -doc.Save("Root1.xml", SaveOptions.DisableFormatting) -Console.WriteLine(File.ReadAllText("Root1.xml")) -doc.Save("Root2.xml", SaveOptions.None) -Console.WriteLine(File.ReadAllText("Root2.xml")) -``` - - This example produces the following output: - -``` -content - - - content - -``` - + flag for `options`. This will cause the writer to write all white space exactly as represented in the XML tree. + + If you want to save indented XML, do not specify the flag for `options`. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the methods that do not take `options` as a parameter. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + + +## Examples + The following example shows two uses of this method. The first use preserves white space. The second one serializes the with indenting. + +```csharp +XDocument doc = new XDocument( + new XElement("Root", + new XElement("Child", "content") + ) +); +doc.Save("Root1.xml", SaveOptions.DisableFormatting); +Console.WriteLine(File.ReadAllText("Root1.xml")); +doc.Save("Root2.xml", SaveOptions.None); +Console.WriteLine(File.ReadAllText("Root2.xml")); +``` + +```vb +Dim doc As XDocument = _ + + content + +doc.Save("Root1.xml", SaveOptions.DisableFormatting) +Console.WriteLine(File.ReadAllText("Root1.xml")) +doc.Save("Root2.xml", SaveOptions.None) +Console.WriteLine(File.ReadAllText("Root2.xml")) +``` + + This example produces the following output: + +``` +content + + + content + +``` + ]]> @@ -2967,6 +2970,7 @@ Console.WriteLine(File.ReadAllText("Root2.xml")) Writes this to an . A task representing the asynchronous save operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -3008,7 +3012,7 @@ Console.WriteLine(File.ReadAllText("Root2.xml")) Output this to a . A task representing the asynchronous save operation. - + The cancellation token was canceled. This exception is stored into the returned task. @@ -3069,6 +3074,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -3111,52 +3117,52 @@ This method stores in the task it returns all non-usage exceptions that the meth An into which this method will write. Write this document to an . - to an . Note that the example did not write an XML declaration. - -```csharp -StringBuilder sb = new StringBuilder(); -XmlWriterSettings xws = new XmlWriterSettings(); -xws.OmitXmlDeclaration = true; -xws.Indent = true; - -using (XmlWriter xw = XmlWriter.Create(sb, xws)) -{ - XDocument doc = new XDocument( - new XElement("Child", - new XElement("GrandChild", "some content") - ) - ); - doc.WriteTo(xw); -} - -Console.WriteLine(sb.ToString()); -``` - -```vb -Dim sb As StringBuilder = New StringBuilder() -Dim xws As XmlWriterSettings = New XmlWriterSettings() -xws.OmitXmlDeclaration = True -xws.Indent = True - -Using xw = XmlWriter.Create(sb, xws) - Dim doc As XDocument = New XDocument(some content) - doc.WriteTo(xw) -End Using - -Console.WriteLine(sb.ToString()) -``` - - This example produces the following output: - -```xml - - some content - -``` - + to an . Note that the example did not write an XML declaration. + +```csharp +StringBuilder sb = new StringBuilder(); +XmlWriterSettings xws = new XmlWriterSettings(); +xws.OmitXmlDeclaration = true; +xws.Indent = true; + +using (XmlWriter xw = XmlWriter.Create(sb, xws)) +{ + XDocument doc = new XDocument( + new XElement("Child", + new XElement("GrandChild", "some content") + ) + ); + doc.WriteTo(xw); +} + +Console.WriteLine(sb.ToString()); +``` + +```vb +Dim sb As StringBuilder = New StringBuilder() +Dim xws As XmlWriterSettings = New XmlWriterSettings() +xws.OmitXmlDeclaration = True +xws.Indent = True + +Using xw = XmlWriter.Create(sb, xws) + Dim doc As XDocument = New XDocument(some content) + doc.WriteTo(xw) +End Using + +Console.WriteLine(sb.ToString()) +``` + + This example produces the following output: + +```xml + + some content + +``` + ]]> @@ -3202,6 +3208,7 @@ Console.WriteLine(sb.ToString()) Writes this XDocument's underlying XML tree to the specified . A task representing the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Xml.Linq/XDocumentType.xml b/xml/System.Xml.Linq/XDocumentType.xml index c3de5781847..8e3a0eb00d3 100644 --- a/xml/System.Xml.Linq/XDocumentType.xml +++ b/xml/System.Xml.Linq/XDocumentType.xml @@ -40,33 +40,33 @@ Represents an XML Document Type Definition (DTD). - with an associated is used to load the XML tree. - - LINQ to XML will not validate a document against a DTD, but you can use a validating to perform DTD validation if necessary. - - To validate an LINQ to XML tree against an XML schema, use the method. - - When a document contains entity references that are defined in a DTD, the references are expanded upon creation of the XML tree. However, when you serialize or save the XML tree, the content of the expanded entities is preserved; the entity references are not. - - Default attributes from the DTD will be materialized as regular attributes in the XML tree. After a default attribute from the DTD is materialized, there is no way to determine that the attribute was a default attribute from the DTD. - - You can populate an XML tree with an XML document that contains an internal DTD. The XML tree will then contain a node. When you serialize or save the tree, the internal DTD will also be saved as part of the document. - + with an associated is used to load the XML tree. + + LINQ to XML will not validate a document against a DTD, but you can use a validating to perform DTD validation if necessary. + + To validate an LINQ to XML tree against an XML schema, use the method. + + When a document contains entity references that are defined in a DTD, the references are expanded upon creation of the XML tree. However, when you serialize or save the XML tree, the content of the expanded entities is preserved; the entity references are not. + + Default attributes from the DTD will be materialized as regular attributes in the XML tree. After a default attribute from the DTD is materialized, there is no way to determine that the attribute was a default attribute from the DTD. + + You can populate an XML tree with an XML document that contains an internal DTD. The XML tree will then contain a node. When you serialize or save the tree, the internal DTD will also be saved as part of the document. + ]]> LINQ to XML overview @@ -121,11 +121,11 @@ An object to copy from. Initializes an instance of the class from another object. - LINQ to XML overview @@ -176,91 +176,91 @@ A that contains the internal subset for an internal DTD. Initializes an instance of the class. - object, it specifies the qualified name of the DTD (Pubs), and a string that contains the internal subset. Because the document does not use a public or private external DTD, the `publicId` and `systemId` are set to `null`. - -```csharp -string internalSubset = @" - - -"; - -string target = "xml-stylesheet"; -string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; - -XDocument doc = new XDocument( - new XComment("This is a comment."), - new XProcessingInstruction(target, data), - new XDocumentType("Pubs", null, null, internalSubset), - new XElement("Pubs", - new XElement("Book", - new XElement("Title", "Artifacts of Roman Civilization"), - new XElement("Author", "Moreno, Jordao") - ), - new XElement("Book", - new XElement("Title", "Midieval Tools and Implements"), - new XElement("Author", "Gazit, Inbar") - ) - ), - new XComment("This is another comment.") -); -doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); - -Console.WriteLine(doc); -``` - -```vb -Dim internalSubset = _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" - -Dim doc As XDocument = _ - - - - - - Artifacts of Roman Civilization - Moreno, Jordao - - - Midieval Tools and Implements - Gazit, Inbar - - - - -doc.FirstNode.NextNode.AddAfterSelf(new XDocumentType("Pubs", Nothing, Nothing, internalSubset)) - -Console.WriteLine(doc) -``` - - This example produces the following output: - -```xml - - - - - -]> - - - Artifacts of Roman Civilization - Moreno, Jordao - - - Midieval Tools and Implements - Gazit, Inbar - - - -``` - + object, it specifies the qualified name of the DTD (Pubs), and a string that contains the internal subset. Because the document does not use a public or private external DTD, the `publicId` and `systemId` are set to `null`. + +```csharp +string internalSubset = @" + + +"; + +string target = "xml-stylesheet"; +string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; + +XDocument doc = new XDocument( + new XComment("This is a comment."), + new XProcessingInstruction(target, data), + new XDocumentType("Pubs", null, null, internalSubset), + new XElement("Pubs", + new XElement("Book", + new XElement("Title", "Artifacts of Roman Civilization"), + new XElement("Author", "Moreno, Jordao") + ), + new XElement("Book", + new XElement("Title", "Midieval Tools and Implements"), + new XElement("Author", "Gazit, Inbar") + ) + ), + new XComment("This is another comment.") +); +doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); + +Console.WriteLine(doc); +``` + +```vb +Dim internalSubset = _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" + +Dim doc As XDocument = _ + + + + + + Artifacts of Roman Civilization + Moreno, Jordao + + + Midieval Tools and Implements + Gazit, Inbar + + + + +doc.FirstNode.NextNode.AddAfterSelf(new XDocumentType("Pubs", Nothing, Nothing, internalSubset)) + +Console.WriteLine(doc) +``` + + This example produces the following output: + +```xml + + + + + +]> + + + Artifacts of Roman Civilization + Moreno, Jordao + + + Midieval Tools and Implements + Gazit, Inbar + + + +``` + ]]> LINQ to XML overview @@ -310,78 +310,78 @@ Console.WriteLine(doc) Gets or sets the internal subset for this Document Type Definition (DTD). A that contains the internal subset for this Document Type Definition (DTD). - - - -"; - -string target = "xml-stylesheet"; -string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; - -XDocument doc = new XDocument( - new XComment("This is a comment."), - new XProcessingInstruction(target, data), - new XDocumentType("Pubs", null, null, internalSubset), - new XElement("Pubs", - new XElement("Book", - new XElement("Title", "Artifacts of Roman Civilization"), - new XElement("Author", "Moreno, Jordao") - ), - new XElement("Book", - new XElement("Title", "Midieval Tools and Implements"), - new XElement("Author", "Gazit, Inbar") - ) - ), - new XComment("This is another comment.") -); -doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); - -Console.WriteLine(doc.DocumentType.InternalSubset); -``` - -```vb -Dim internalSubset = _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" - -Dim doc As XDocument = _ - - - - - - Artifacts of Roman Civilization - Moreno, Jordao - - - Midieval Tools and Implements - Gazit, Inbar - - - - -doc.FirstNode.AddAfterSelf(new XDocumentType("Pubs", Nothing, Nothing, internalSubset)) - -Console.WriteLine(doc.DocumentType.InternalSubset) -``` - - This example produces the following output: - -``` - - - - -``` - + + + +"; + +string target = "xml-stylesheet"; +string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; + +XDocument doc = new XDocument( + new XComment("This is a comment."), + new XProcessingInstruction(target, data), + new XDocumentType("Pubs", null, null, internalSubset), + new XElement("Pubs", + new XElement("Book", + new XElement("Title", "Artifacts of Roman Civilization"), + new XElement("Author", "Moreno, Jordao") + ), + new XElement("Book", + new XElement("Title", "Midieval Tools and Implements"), + new XElement("Author", "Gazit, Inbar") + ) + ), + new XComment("This is another comment.") +); +doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); + +Console.WriteLine(doc.DocumentType.InternalSubset); +``` + +```vb +Dim internalSubset = _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" + +Dim doc As XDocument = _ + + + + + + Artifacts of Roman Civilization + Moreno, Jordao + + + Midieval Tools and Implements + Gazit, Inbar + + + + +doc.FirstNode.AddAfterSelf(new XDocumentType("Pubs", Nothing, Nothing, internalSubset)) + +Console.WriteLine(doc.DocumentType.InternalSubset) +``` + + This example produces the following output: + +``` + + + + +``` + ]]> LINQ to XML overview @@ -430,75 +430,75 @@ Console.WriteLine(doc.DocumentType.InternalSubset) Gets or sets the name for this Document Type Definition (DTD). A that contains the name for this Document Type Definition (DTD). - - - -"; - -string target = "xml-stylesheet"; -string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; - -XDocument doc = new XDocument( - new XComment("This is a comment."), - new XProcessingInstruction(target, data), - new XDocumentType("Pubs", null, null, internalSubset), - new XElement("Pubs", - new XElement("Book", - new XElement("Title", "Artifacts of Roman Civilization"), - new XElement("Author", "Moreno, Jordao") - ), - new XElement("Book", - new XElement("Title", "Midieval Tools and Implements"), - new XElement("Author", "Gazit, Inbar") - ) - ), - new XComment("This is another comment.") -); -doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); - -Console.WriteLine(doc.DocumentType.Name); -``` - -```vb -Dim internalSubset = _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" - -Dim doc As XDocument = _ - - - - - - Artifacts of Roman Civilization - Moreno, Jordao - - - Midieval Tools and Implements - Gazit, Inbar - - - - -doc.FirstNode.AddAfterSelf(new XDocumentType("Pubs", Nothing, Nothing, internalSubset)) - -Console.WriteLine(doc.DocumentType.Name) -``` - - This example produces the following output: - -``` -Pubs -``` - + + + +"; + +string target = "xml-stylesheet"; +string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; + +XDocument doc = new XDocument( + new XComment("This is a comment."), + new XProcessingInstruction(target, data), + new XDocumentType("Pubs", null, null, internalSubset), + new XElement("Pubs", + new XElement("Book", + new XElement("Title", "Artifacts of Roman Civilization"), + new XElement("Author", "Moreno, Jordao") + ), + new XElement("Book", + new XElement("Title", "Midieval Tools and Implements"), + new XElement("Author", "Gazit, Inbar") + ) + ), + new XComment("This is another comment.") +); +doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); + +Console.WriteLine(doc.DocumentType.Name); +``` + +```vb +Dim internalSubset = _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" + +Dim doc As XDocument = _ + + + + + + Artifacts of Roman Civilization + Moreno, Jordao + + + Midieval Tools and Implements + Gazit, Inbar + + + + +doc.FirstNode.AddAfterSelf(new XDocumentType("Pubs", Nothing, Nothing, internalSubset)) + +Console.WriteLine(doc.DocumentType.Name) +``` + + This example produces the following output: + +``` +Pubs +``` + ]]> LINQ to XML overview @@ -541,80 +541,80 @@ Pubs Gets the node type for this node. The node type. For objects, this value is . - contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. - - - -## Examples - The following example shows the use of this property to retrieve the node type for an object. - -```csharp -string internalSubset = @" - - -"; - -string target = "xml-stylesheet"; -string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; - -XDocument doc = new XDocument( - new XComment("This is a comment."), - new XProcessingInstruction(target, data), - new XDocumentType("Pubs", null, null, internalSubset), - new XElement("Pubs", - new XElement("Book", - new XElement("Title", "Artifacts of Roman Civilization"), - new XElement("Author", "Moreno, Jordao") - ), - new XElement("Book", - new XElement("Title", "Midieval Tools and Implements"), - new XElement("Author", "Gazit, Inbar") - ) - ), - new XComment("This is another comment.") -); -doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); - -Console.WriteLine(doc.DocumentType.NodeType); -``` - -```vb -Dim internalSubset = _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" - -Dim doc As XDocument = _ - - - - - - Artifacts of Roman Civilization - Moreno, Jordao - - - Midieval Tools and Implements - Gazit, Inbar - - - - -doc.FirstNode.AddAfterSelf(new XDocumentType("Pubs", Nothing, Nothing, internalSubset)) - -Console.WriteLine(doc.DocumentType.NodeType.ToString()) -``` - - This example produces the following output: - -``` -DocumentType -``` - + contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. + + + +## Examples + The following example shows the use of this property to retrieve the node type for an object. + +```csharp +string internalSubset = @" + + +"; + +string target = "xml-stylesheet"; +string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; + +XDocument doc = new XDocument( + new XComment("This is a comment."), + new XProcessingInstruction(target, data), + new XDocumentType("Pubs", null, null, internalSubset), + new XElement("Pubs", + new XElement("Book", + new XElement("Title", "Artifacts of Roman Civilization"), + new XElement("Author", "Moreno, Jordao") + ), + new XElement("Book", + new XElement("Title", "Midieval Tools and Implements"), + new XElement("Author", "Gazit, Inbar") + ) + ), + new XComment("This is another comment.") +); +doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); + +Console.WriteLine(doc.DocumentType.NodeType); +``` + +```vb +Dim internalSubset = _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" + +Dim doc As XDocument = _ + + + + + + Artifacts of Roman Civilization + Moreno, Jordao + + + Midieval Tools and Implements + Gazit, Inbar + + + + +doc.FirstNode.AddAfterSelf(new XDocumentType("Pubs", Nothing, Nothing, internalSubset)) + +Console.WriteLine(doc.DocumentType.NodeType.ToString()) +``` + + This example produces the following output: + +``` +DocumentType +``` + ]]> LINQ to XML overview @@ -664,11 +664,11 @@ DocumentType Gets or sets the public identifier for this Document Type Definition (DTD). A that contains the public identifier for this Document Type Definition (DTD). - LINQ to XML overview @@ -718,106 +718,106 @@ DocumentType Gets or sets the system identifier for this Document Type Definition (DTD). A that contains the system identifier for this Document Type Definition (DTD). - constructor reflects the use of the external private DTD. It passes `null` for the internal subset. - -```csharp -string pubsDtd = -@" - - -"; -File.WriteAllText("Pubs.dtd", pubsDtd); - -string target = "xml-stylesheet"; -string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; - -XDocument doc = new XDocument( - new XDocumentType("Pubs", null, "Pubs.dtd", null), - new XElement("Pubs", - new XElement("Book", - new XElement("Title", "Artifacts of Roman Civilization"), - new XElement("Author", "Moreno, Jordao") - ), - new XElement("Book", - new XElement("Title", "Midieval Tools and Implements"), - new XElement("Author", "Gazit, Inbar") - ) - ), - new XComment("This is another comment.") -); -doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); -doc.Save("Pubs.xml"); - -// Validate Pubs.xml against Pubs.dtd. -XmlReaderSettings xrs = new XmlReaderSettings(); -xrs.ProhibitDtd = false; -xrs.ValidationType = ValidationType.DTD; -xrs.ConformanceLevel = ConformanceLevel.Auto; -XmlReader xr = XmlReader.Create("Pubs.xml", xrs); -XDocument doc2 = XDocument.Load(xr); - -XDocumentType dt = doc2.Document.DocumentType; -Console.WriteLine("SystemId:{0}", dt.SystemId); -``` - -```vb -Dim pubsDtd As String = _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" & Environment.NewLine & _ - "" -File.WriteAllText("Pubs.dtd", pubsDtd) - -Dim target As String = "xml-stylesheet" -Dim data As String = "href='mystyle.css' title='Compact' type='text/css'" - -Dim doc As XDocument = _ - - - - Artifacts of Roman Civilization - Moreno, Jordao - - - Midieval Tools and Implements - Gazit, Inbar - - - - -doc _ -.FirstNode _ -.AddBeforeSelf(New XDocumentType("Pubs", Nothing, "Pubs.dtd", Nothing)) - -doc.Declaration = New XDeclaration("1.0", "utf-8", "true") -doc.Save("Pubs.xml") - -' Validate Pubs.xml against Pubs.dtd. -Dim xrs As XmlReaderSettings = New XmlReaderSettings() -xrs.ProhibitDtd = False -xrs.ValidationType = ValidationType.DTD -xrs.ConformanceLevel = ConformanceLevel.Auto -Dim xr As XmlReader = XmlReader.Create("Pubs.xml", xrs) -Dim doc2 As XDocument = XDocument.Load(xr) - -Dim dt As XDocumentType = doc2.Document.DocumentType -Console.WriteLine("SystemId:{0}", dt.SystemId) -``` - - This example produces the following output: - -``` -SystemId:Pubs.dtd -``` - + constructor reflects the use of the external private DTD. It passes `null` for the internal subset. + +```csharp +string pubsDtd = +@" + + +"; +File.WriteAllText("Pubs.dtd", pubsDtd); + +string target = "xml-stylesheet"; +string data = "href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""; + +XDocument doc = new XDocument( + new XDocumentType("Pubs", null, "Pubs.dtd", null), + new XElement("Pubs", + new XElement("Book", + new XElement("Title", "Artifacts of Roman Civilization"), + new XElement("Author", "Moreno, Jordao") + ), + new XElement("Book", + new XElement("Title", "Midieval Tools and Implements"), + new XElement("Author", "Gazit, Inbar") + ) + ), + new XComment("This is another comment.") +); +doc.Declaration = new XDeclaration("1.0", "utf-8", "true"); +doc.Save("Pubs.xml"); + +// Validate Pubs.xml against Pubs.dtd. +XmlReaderSettings xrs = new XmlReaderSettings(); +xrs.ProhibitDtd = false; +xrs.ValidationType = ValidationType.DTD; +xrs.ConformanceLevel = ConformanceLevel.Auto; +XmlReader xr = XmlReader.Create("Pubs.xml", xrs); +XDocument doc2 = XDocument.Load(xr); + +XDocumentType dt = doc2.Document.DocumentType; +Console.WriteLine("SystemId:{0}", dt.SystemId); +``` + +```vb +Dim pubsDtd As String = _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" & Environment.NewLine & _ + "" +File.WriteAllText("Pubs.dtd", pubsDtd) + +Dim target As String = "xml-stylesheet" +Dim data As String = "href='mystyle.css' title='Compact' type='text/css'" + +Dim doc As XDocument = _ + + + + Artifacts of Roman Civilization + Moreno, Jordao + + + Midieval Tools and Implements + Gazit, Inbar + + + + +doc _ +.FirstNode _ +.AddBeforeSelf(New XDocumentType("Pubs", Nothing, "Pubs.dtd", Nothing)) + +doc.Declaration = New XDeclaration("1.0", "utf-8", "true") +doc.Save("Pubs.xml") + +' Validate Pubs.xml against Pubs.dtd. +Dim xrs As XmlReaderSettings = New XmlReaderSettings() +xrs.ProhibitDtd = False +xrs.ValidationType = ValidationType.DTD +xrs.ConformanceLevel = ConformanceLevel.Auto +Dim xr As XmlReader = XmlReader.Create("Pubs.xml", xrs) +Dim doc2 As XDocument = XDocument.Load(xr) + +Dim dt As XDocumentType = doc2.Document.DocumentType +Console.WriteLine("SystemId:{0}", dt.SystemId) +``` + + This example produces the following output: + +``` +SystemId:Pubs.dtd +``` + ]]> LINQ to XML overview @@ -863,11 +863,11 @@ SystemId:Pubs.dtd An into which this method will write. Write this to an . - . - + . + ]]> LINQ to XML overview @@ -910,6 +910,7 @@ SystemId:Pubs.dtd Writes this to the specified . A task representing the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Xml.Linq/XElement.xml b/xml/System.Xml.Linq/XElement.xml index ec8359b2702..5e139317366 100644 --- a/xml/System.Xml.Linq/XElement.xml +++ b/xml/System.Xml.Linq/XElement.xml @@ -71,141 +71,141 @@ Represents an XML element. See XElement Class Overview and the Remarks section on this page for usage information and examples. - , optionally one or more attributes, and can optionally contain content (for more information, see ). - - An can contain the following types of content: - -- - -- - -- - -- - - For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - - derives from , which derives from . - - Some methods can be used from XAML. For more information, see [LINQ to XML Dynamic Properties](/dotnet/desktop/wpf/data/linq-to-xml-dynamic-properties). - - - -## Examples - The following example creates an XML tree. The content of the new element comes from a LINQ query. - -```csharp -XElement xmlTree1 = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5), - new XElement("Child6", 6) -); - -XElement xmlTree2 = new XElement("Root", - from el in xmlTree1.Elements() - where((int)el >= 3 && (int)el <= 5) - select el -); -Console.WriteLine(xmlTree2); -``` - -```vb -Dim xmlTree1 As XElement = _ - - 1 - 2 - 3 - 4 - 5 - 6 - - -Dim xmlTree2 As XElement = _ - - <%= From el In xmlTree1.Elements() _ - Where el.Value >= 3 And el.Value <= 5 _ - Select el %> - - -Console.WriteLine(xmlTree2) -``` - - This example produces the following output: - -```xml - - 3 - 4 - 5 - -``` - - The following is the same example, but in this case the XML is in a namespace. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). - -```csharp -XNamespace aw = "http://www.adventure-works.com"; -XElement xmlTree1 = new XElement(aw + "Root", - new XElement(aw + "Child1", 1), - new XElement(aw + "Child2", 2), - new XElement(aw + "Child3", 3), - new XElement(aw + "Child4", 4), - new XElement(aw + "Child5", 5), - new XElement(aw + "Child6", 6) -); - -XElement xmlTree2 = new XElement(aw + "Root", - from el in xmlTree1.Elements() - where((int)el >= 3 && (int)el <= 5) - select el -); -Console.WriteLine(xmlTree2); -``` - -```vb -Imports - -Module Module1 - Sub Main() - Dim xmlTree1 As XElement = _ - - 1 - 2 - 3 - 4 - 5 - 6 - - - Dim xmlTree2 As XElement = _ - - <%= From el In xmlTree1.Elements() _ - Where el.Value >= 3 And el.Value <= 5 _ - Select el %> - - - Console.WriteLine(xmlTree2) - End SUb -End Module -``` - - This example produces the following output: - -```xml - - 3 - 4 - 5 - -``` - + , optionally one or more attributes, and can optionally contain content (for more information, see ). + + An can contain the following types of content: + +- + +- + +- + +- + + For details about the valid content of an , see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + + derives from , which derives from . + + Some methods can be used from XAML. For more information, see [LINQ to XML Dynamic Properties](/dotnet/desktop/wpf/data/linq-to-xml-dynamic-properties). + + + +## Examples + The following example creates an XML tree. The content of the new element comes from a LINQ query. + +```csharp +XElement xmlTree1 = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5), + new XElement("Child6", 6) +); + +XElement xmlTree2 = new XElement("Root", + from el in xmlTree1.Elements() + where((int)el >= 3 && (int)el <= 5) + select el +); +Console.WriteLine(xmlTree2); +``` + +```vb +Dim xmlTree1 As XElement = _ + + 1 + 2 + 3 + 4 + 5 + 6 + + +Dim xmlTree2 As XElement = _ + + <%= From el In xmlTree1.Elements() _ + Where el.Value >= 3 And el.Value <= 5 _ + Select el %> + + +Console.WriteLine(xmlTree2) +``` + + This example produces the following output: + +```xml + + 3 + 4 + 5 + +``` + + The following is the same example, but in this case the XML is in a namespace. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). + +```csharp +XNamespace aw = "http://www.adventure-works.com"; +XElement xmlTree1 = new XElement(aw + "Root", + new XElement(aw + "Child1", 1), + new XElement(aw + "Child2", 2), + new XElement(aw + "Child3", 3), + new XElement(aw + "Child4", 4), + new XElement(aw + "Child5", 5), + new XElement(aw + "Child6", 6) +); + +XElement xmlTree2 = new XElement(aw + "Root", + from el in xmlTree1.Elements() + where((int)el >= 3 && (int)el <= 5) + select el +); +Console.WriteLine(xmlTree2); +``` + +```vb +Imports + +Module Module1 + Sub Main() + Dim xmlTree1 As XElement = _ + + 1 + 2 + 3 + 4 + 5 + 6 + + + Dim xmlTree2 As XElement = _ + + <%= From el In xmlTree1.Elements() _ + Where el.Value >= 3 And el.Value <= 5 _ + Select el %> + + + Console.WriteLine(xmlTree2) + End SUb +End Module +``` + + This example produces the following output: + +```xml + + 3 + 4 + 5 + +``` + ]]> LINQ to XML overview @@ -221,69 +221,69 @@ End Module Initializes a new instance of the class. - . Typical use of this constructor is to specify a string as the parameter instead of creating a new . - - When creating an element in a namespace, typical use is to use the addition operator overload with an and a string to create an . For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). - - - -## Examples - The following example creates an XML tree. The content of the new element comes from a LINQ query. - -```csharp -XElement xmlTree1 = new XElement("Root", - new XElement("Child", 1), - new XElement("Child", 2), - new XElement("Child", 3), - new XElement("Child", 4), - new XElement("Child", 5), - new XElement("Child", 6) -); - -XElement xmlTree2 = new XElement("Root", - from el in xmlTree1.Elements() - where((int)el >= 3 && (int)el <= 5) - select el -); -Console.WriteLine(xmlTree2); -``` - -```vb -Dim xmlTree1 As XElement = _ - - 1 - 2 - 3 - 4 - 5 - 6 - - -Dim xmlTree2 As XElement = _ - - <%= From el In xmlTree1.Elements() _ - Where el.Value >= 3 And el.Value <= 5 _ - Select el %> - - -Console.WriteLine(xmlTree2) -``` - - This example produces the following output: - -```xml - - 3 - 4 - 5 - -``` - + . Typical use of this constructor is to specify a string as the parameter instead of creating a new . + + When creating an element in a namespace, typical use is to use the addition operator overload with an and a string to create an . For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). + + + +## Examples + The following example creates an XML tree. The content of the new element comes from a LINQ query. + +```csharp +XElement xmlTree1 = new XElement("Root", + new XElement("Child", 1), + new XElement("Child", 2), + new XElement("Child", 3), + new XElement("Child", 4), + new XElement("Child", 5), + new XElement("Child", 6) +); + +XElement xmlTree2 = new XElement("Root", + from el in xmlTree1.Elements() + where((int)el >= 3 && (int)el <= 5) + select el +); +Console.WriteLine(xmlTree2); +``` + +```vb +Dim xmlTree1 As XElement = _ + + 1 + 2 + 3 + 4 + 5 + 6 + + +Dim xmlTree2 As XElement = _ + + <%= From el In xmlTree1.Elements() _ + Where el.Value >= 3 And el.Value <= 5 _ + Select el %> + + +Console.WriteLine(xmlTree2) +``` + + This example produces the following output: + +```xml + + 3 + 4 + 5 + +``` + ]]> LINQ to XML overview @@ -326,59 +326,59 @@ Console.WriteLine(xmlTree2) An object to copy from. Initializes a new instance of the class from another object. - , which tests whether the two XML trees are equal. - -```csharp -XElement xmlTree = new XElement("Root", - new XAttribute("Att1", 1), - new XElement("Child1", 1), - new XElement("Child2", 2) -); - -// Create a clone of the tree. -XElement treeClone = new XElement(xmlTree); - -Console.WriteLine("xmlTree = treeClone: {0}", XNode.DeepEquals(xmlTree, treeClone)); - -// Do some work with xmlTree, perhaps pass it to other methods. -xmlTree.Add(new XElement("Child3", 3)); - -Console.WriteLine("xmlTree = treeClone: {0}", XNode.DeepEquals(xmlTree, treeClone)); -``` - -```vb -Dim xmlTree As XElement = _ - - 1 - 2 - - -' Create a clone of the tree. -Dim treeClone As XElement = New XElement(xmlTree) - -Console.WriteLine("xmlTree = treeClone: {0}", XNode.DeepEquals(xmlTree, treeClone)) - -' Do some work with xmlTree, perhaps pass it to other methods. -xmlTree.Add(New XElement("Child3", 3)) - -Console.WriteLine("xmlTree = treeClone: {0}", XNode.DeepEquals(xmlTree, treeClone)) -``` - - This example produces the following output: - -``` -xmlTree = treeClone: True -xmlTree = treeClone: False -``` - + , which tests whether the two XML trees are equal. + +```csharp +XElement xmlTree = new XElement("Root", + new XAttribute("Att1", 1), + new XElement("Child1", 1), + new XElement("Child2", 2) +); + +// Create a clone of the tree. +XElement treeClone = new XElement(xmlTree); + +Console.WriteLine("xmlTree = treeClone: {0}", XNode.DeepEquals(xmlTree, treeClone)); + +// Do some work with xmlTree, perhaps pass it to other methods. +xmlTree.Add(new XElement("Child3", 3)); + +Console.WriteLine("xmlTree = treeClone: {0}", XNode.DeepEquals(xmlTree, treeClone)); +``` + +```vb +Dim xmlTree As XElement = _ + + 1 + 2 + + +' Create a clone of the tree. +Dim treeClone As XElement = New XElement(xmlTree) + +Console.WriteLine("xmlTree = treeClone: {0}", XNode.DeepEquals(xmlTree, treeClone)) + +' Do some work with xmlTree, perhaps pass it to other methods. +xmlTree.Add(New XElement("Child3", 3)) + +Console.WriteLine("xmlTree = treeClone: {0}", XNode.DeepEquals(xmlTree, treeClone)) +``` + + This example produces the following output: + +``` +xmlTree = treeClone: True +xmlTree = treeClone: False +``` + ]]> LINQ to XML overview @@ -421,59 +421,59 @@ xmlTree = treeClone: False An that contains the name of the element. Initializes a new instance of the class with the specified name. - . Typical use of this constructor is to specify a string as the parameter instead of creating a new . When creating an element in a namespace, typical use is to use the addition operator overload with an and a string to create an . For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). - - - -## Examples - The following example creates an element with no content. - -```csharp -XElement el = new XElement("Root"); -Console.WriteLine(el); -``` - -```vb -Dim el As XElement = -Console.WriteLine(el) -``` - - This example produces the following output: - -```xml - -``` - - The following example creates an element in a namespace with no content. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). - + . Typical use of this constructor is to specify a string as the parameter instead of creating a new . When creating an element in a namespace, typical use is to use the addition operator overload with an and a string to create an . For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). + + + +## Examples + The following example creates an element with no content. + ```csharp -XNamespace aw = "http://www.adventure-works.com"; -XElement root = new XElement(aw + "Root"); -Console.WriteLine(root); -``` - -```vb -Imports - -Module Module1 - Sub Main() - Dim root = - Console.WriteLine(root) - End Sub -End Module -``` - - This example produces the following output: - -```xml - -``` - +XElement el = new XElement("Root"); +Console.WriteLine(el); +``` + +```vb +Dim el As XElement = +Console.WriteLine(el) +``` + + This example produces the following output: + +```xml + +``` + + The following example creates an element in a namespace with no content. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). + +```csharp +XNamespace aw = "http://www.adventure-works.com"; +XElement root = new XElement(aw + "Root"); +Console.WriteLine(root); +``` + +```vb +Imports + +Module Module1 + Sub Main() + Dim root = + Console.WriteLine(root) + End Sub +End Module +``` + + This example produces the following output: + +```xml + +``` + ]]> LINQ to XML overview @@ -516,66 +516,66 @@ End Module An that contains unevaluated queries that will be iterated for the contents of this . Initializes a new instance of the class from an object. - , and creates an element with its contents. - - - -## Examples - The following example creates a source XML tree, and then creates an from a query on the source XML tree. It then serializes the to the console, adds a new element to the source XML tree, and then serializes the again. You can see that element newly added to the source XML tree is not included in the first serialization, but is included in the second. - -```csharp -XElement src = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3) - ); -XStreamingElement xse = new XStreamingElement("NewRoot", - from el in src.Elements() - where (int)el >= 2 - select el - ); -Console.WriteLine(xse); -src.Add(new XElement("Child4", 4)); -Console.WriteLine("----"); -Console.WriteLine(xse); -``` - -```vb -Dim src As XElement = _ - - 1 - 2 - 3 - -Dim xse As XStreamingElement = New XStreamingElement("NewRoot", _ - From el In src.Elements() _ - Where (CInt(el) >= 2) _ - Select el _ -) -Console.WriteLine(xse) -src.Add(New XElement("Child4", 4)) -Console.WriteLine("----") -Console.WriteLine(xse) -``` - - This example produces the following output: - -``` - - 2 - 3 - ----- - - 2 - 3 - 4 - -``` - + , and creates an element with its contents. + + + +## Examples + The following example creates a source XML tree, and then creates an from a query on the source XML tree. It then serializes the to the console, adds a new element to the source XML tree, and then serializes the again. You can see that element newly added to the source XML tree is not included in the first serialization, but is included in the second. + +```csharp +XElement src = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3) + ); +XStreamingElement xse = new XStreamingElement("NewRoot", + from el in src.Elements() + where (int)el >= 2 + select el + ); +Console.WriteLine(xse); +src.Add(new XElement("Child4", 4)); +Console.WriteLine("----"); +Console.WriteLine(xse); +``` + +```vb +Dim src As XElement = _ + + 1 + 2 + 3 + +Dim xse As XStreamingElement = New XStreamingElement("NewRoot", _ + From el In src.Elements() _ + Where (CInt(el) >= 2) _ + Select el _ +) +Console.WriteLine(xse) +src.Add(New XElement("Child4", 4)) +Console.WriteLine("----") +Console.WriteLine(xse) +``` + + This example produces the following output: + +``` + + 2 + 3 + +---- + + 2 + 3 + 4 + +``` + ]]> LINQ to XML overview @@ -621,277 +621,277 @@ Console.WriteLine(xse) The contents of the element. Initializes a new instance of the class with the specified name and content. - . Typical use of this constructor is to specify a string as the parameter instead of creating a new . - - When creating an element in a namespace, typical use is to use the addition operator overload with an and a string to create an . For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). - - For details about the valid content that can be passed to this constructor, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - - - -## Examples - The following example creates an XML tree. The content of the new element comes from a LINQ query. - -```csharp -XElement xmlTree1 = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5), - new XElement("Child6", 6) -); - -XElement xmlTree2 = new XElement("Root", - from el in xmlTree1.Elements() - where((int)el >= 3 && (int)el <= 5) - select el -); -Console.WriteLine(xmlTree2); -``` - -```vb -Dim xmlTree1 As XElement = _ - - 1 - 2 - 3 - 4 - 5 - 6 - - -Dim xmlTree2 As XElement = _ - - <%= From el In xmlTree1.Elements() _ - Where el.Value >= 3 And el.Value <= 5 _ - Select el %> - - -Console.WriteLine(xmlTree2) -``` - - This example produces the following output: - -```xml - - 3 - 4 - 5 - -``` - - The following example creates an XML tree with a variety of types of content. - -```csharp -XElement root; - -// String content: -root = new XElement("Root", "Some text"); -Console.WriteLine(root); - -// XElement object content: -root = new XElement("Root", - new XElement("NewChild", "n") -); -Console.WriteLine(root); - -// XAttribute object content: -root = new XElement("Root", - new XAttribute("NewAttribute", "n") -); -Console.WriteLine(root); - -// Double content: -double dbl = 12.345; -root = new XElement("Root", dbl); -Console.WriteLine(root); - -// DateTime content: -DateTime dt = new DateTime(2006, 10, 6, 12, 30, 00); -root = new XElement("Root", dt); -Console.WriteLine(root); - -// String array content: -// Any collection other than a collection of XElement or XAttribute objects -// are converted to strings. The strings are concatenated and added. -string[] stringArray = { - "abc", - "def", - "ghi" -}; -root = new XElement("Root", stringArray); -Console.WriteLine(root); - -// XElement object array content: -XElement[] ellArray = { - new XElement("NewChild1", 1), - new XElement("NewChild2", 2), - new XElement("NewChild3", 3) -}; -root = new XElement("Root", ellArray); -Console.WriteLine(root); - -// XAttribute object array content: -XAttribute[] attArray = { - new XAttribute("NewAtt1", 1), - new XAttribute("NewAtt2", 2), - new XAttribute("NewAtt3", 3) -}; -root = new XElement("Root", attArray); -Console.WriteLine(root); -``` - -```vb -Dim root As XElement - -' String content: -root = Some text -Console.WriteLine(root) - -' XElement object content: -root = - n - -Console.WriteLine(root) - -' XAttribute object content: -root = -Console.WriteLine(root) - -' Double content: -Dim dbl As Double = 12.345 -root = <%= dbl %> -Console.WriteLine(root) - -' DateTime content: -Dim dt As DateTime = New DateTime(2006, 10, 6, 12, 30, 0) -root = <%= dt %> -Console.WriteLine(root) - -' String array content: -' Any collection other than a collection of XElement or XAttribute objects -' are converted to strings. The strings are concatenated and added. - -Dim stringArray As String() = { _ - "abc", _ - "def", _ - "ghi" _ -} -root = <%= stringArray %> -Console.WriteLine(root) - -' XElement object array content: -Dim ellArray As XElement() = { _ - 1, _ - 2, _ - 3 _ -} - -root = <%= ellArray %> -Console.WriteLine(root) - -' XAttribute object array content -Dim attArray As XAttribute() = { _ - New XAttribute("NewAtt1", 1), _ - New XAttribute("NewAtt2", 2), _ - New XAttribute("NewAtt3", 3) _ -} -root = <%= attArray %> -Console.WriteLine(root) -``` - - This example produces the following output: - + . Typical use of this constructor is to specify a string as the parameter instead of creating a new . + + When creating an element in a namespace, typical use is to use the addition operator overload with an and a string to create an . For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). + + For details about the valid content that can be passed to this constructor, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + + + +## Examples + The following example creates an XML tree. The content of the new element comes from a LINQ query. + +```csharp +XElement xmlTree1 = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5), + new XElement("Child6", 6) +); + +XElement xmlTree2 = new XElement("Root", + from el in xmlTree1.Elements() + where((int)el >= 3 && (int)el <= 5) + select el +); +Console.WriteLine(xmlTree2); +``` + +```vb +Dim xmlTree1 As XElement = _ + + 1 + 2 + 3 + 4 + 5 + 6 + + +Dim xmlTree2 As XElement = _ + + <%= From el In xmlTree1.Elements() _ + Where el.Value >= 3 And el.Value <= 5 _ + Select el %> + + +Console.WriteLine(xmlTree2) +``` + + This example produces the following output: + ```xml -Some text - - n - - -12.345 -2006-10-06T12:30:00 -abcdefghi - - 1 - 2 - 3 - - -``` - - The following example creates an XML tree in a namespace. - -```csharp -// Create an XML tree in a namespace. -XNamespace aw = "http://www.adventure-works.com"; -XElement root = new XElement(aw + "Root", - new XElement(aw + "Child", "child content") -); -Console.WriteLine(root); -``` - -```vb -' Create an XML tree in a namespace. -Dim root As XElement = _ - - child content - -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - - child content - -``` - - The following example creates an XML tree with nested namespaces. - -```csharp -// Create an XML tree with nested namespaces. -XNamespace aw = "http://www.adventure-works.com"; -XNamespace fc = "www.fourthcoffee.com"; -XDocument root = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - new XElement(aw + "Root", - new XElement(fc + "Child", - new XElement(aw + "DifferentChild", "other content") - ) - ) -); -Console.WriteLine(root); -``` - -```vb -' Create an XML tree with nested namespaces. -Dim root As XDocument = _ - - - - other content - - -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - - - other content - - -``` - + + 3 + 4 + 5 + +``` + + The following example creates an XML tree with a variety of types of content. + +```csharp +XElement root; + +// String content: +root = new XElement("Root", "Some text"); +Console.WriteLine(root); + +// XElement object content: +root = new XElement("Root", + new XElement("NewChild", "n") +); +Console.WriteLine(root); + +// XAttribute object content: +root = new XElement("Root", + new XAttribute("NewAttribute", "n") +); +Console.WriteLine(root); + +// Double content: +double dbl = 12.345; +root = new XElement("Root", dbl); +Console.WriteLine(root); + +// DateTime content: +DateTime dt = new DateTime(2006, 10, 6, 12, 30, 00); +root = new XElement("Root", dt); +Console.WriteLine(root); + +// String array content: +// Any collection other than a collection of XElement or XAttribute objects +// are converted to strings. The strings are concatenated and added. +string[] stringArray = { + "abc", + "def", + "ghi" +}; +root = new XElement("Root", stringArray); +Console.WriteLine(root); + +// XElement object array content: +XElement[] ellArray = { + new XElement("NewChild1", 1), + new XElement("NewChild2", 2), + new XElement("NewChild3", 3) +}; +root = new XElement("Root", ellArray); +Console.WriteLine(root); + +// XAttribute object array content: +XAttribute[] attArray = { + new XAttribute("NewAtt1", 1), + new XAttribute("NewAtt2", 2), + new XAttribute("NewAtt3", 3) +}; +root = new XElement("Root", attArray); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement + +' String content: +root = Some text +Console.WriteLine(root) + +' XElement object content: +root = + n + +Console.WriteLine(root) + +' XAttribute object content: +root = +Console.WriteLine(root) + +' Double content: +Dim dbl As Double = 12.345 +root = <%= dbl %> +Console.WriteLine(root) + +' DateTime content: +Dim dt As DateTime = New DateTime(2006, 10, 6, 12, 30, 0) +root = <%= dt %> +Console.WriteLine(root) + +' String array content: +' Any collection other than a collection of XElement or XAttribute objects +' are converted to strings. The strings are concatenated and added. + +Dim stringArray As String() = { _ + "abc", _ + "def", _ + "ghi" _ +} +root = <%= stringArray %> +Console.WriteLine(root) + +' XElement object array content: +Dim ellArray As XElement() = { _ + 1, _ + 2, _ + 3 _ +} + +root = <%= ellArray %> +Console.WriteLine(root) + +' XAttribute object array content +Dim attArray As XAttribute() = { _ + New XAttribute("NewAtt1", 1), _ + New XAttribute("NewAtt2", 2), _ + New XAttribute("NewAtt3", 3) _ +} +root = <%= attArray %> +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml +Some text + + n + + +12.345 +2006-10-06T12:30:00 +abcdefghi + + 1 + 2 + 3 + + +``` + + The following example creates an XML tree in a namespace. + +```csharp +// Create an XML tree in a namespace. +XNamespace aw = "http://www.adventure-works.com"; +XElement root = new XElement(aw + "Root", + new XElement(aw + "Child", "child content") +); +Console.WriteLine(root); +``` + +```vb +' Create an XML tree in a namespace. +Dim root As XElement = _ + + child content + +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + + child content + +``` + + The following example creates an XML tree with nested namespaces. + +```csharp +// Create an XML tree with nested namespaces. +XNamespace aw = "http://www.adventure-works.com"; +XNamespace fc = "www.fourthcoffee.com"; +XDocument root = new XDocument( + new XDeclaration("1.0", "utf-8", "yes"), + new XElement(aw + "Root", + new XElement(fc + "Child", + new XElement(aw + "DifferentChild", "other content") + ) + ) +); +Console.WriteLine(root); +``` + +```vb +' Create an XML tree with nested namespaces. +Dim root As XDocument = _ + + + + other content + + +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + + + other content + + +``` + ]]> LINQ to XML overview @@ -950,274 +950,274 @@ Console.WriteLine(root) The initial content of the element. Initializes a new instance of the class with the specified name and content. - . Typical use of this constructor is to specify a string as the parameter instead of creating a new . - - When creating an element in a namespace, typical use is to use the addition operator overload with an and a string to create an . For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). - - For details about the valid content that can be passed to this constructor, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - - - -## Examples - The following example creates an XML tree. The content of the new element comes from a LINQ query. - -```csharp -XElement xmlTree1 = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5), - new XElement("Child6", 6) -); - -XElement xmlTree2 = new XElement("Root", - from el in xmlTree1.Elements() - where((int)el >= 3 && (int)el <= 5) - select el -); -Console.WriteLine(xmlTree2); -``` - -```vb -Dim xmlTree1 As XElement = _ - - 1 - 2 - 3 - 4 - 5 - 6 - - -Dim xmlTree2 As XElement = _ - - <%= From el In xmlTree1.Elements() _ - Where el.Value >= 3 And el.Value <= 5 _ - Select el %> - - -Console.WriteLine(xmlTree2) -``` - - This example produces the following output: - -```xml - - 3 - 4 - 5 - -``` - - The following example creates an XML tree with a variety of types of content. - -```csharp -XElement root; - -// String content: -root = new XElement("Root", "Some text"); -Console.WriteLine(root); - -// XElement object content: -root = new XElement("Root", - new XElement("NewChild", "n") -); -Console.WriteLine(root); - -// XAttribute object content: -root = new XElement("Root", - new XAttribute("NewAttribute", "n") -); -Console.WriteLine(root); - -// Double content: -double dbl = 12.345; -root = new XElement("Root", dbl); -Console.WriteLine(root); - -// DateTime content: -DateTime dt = new DateTime(2006, 10, 6, 12, 30, 00); -root = new XElement("Root", dt); -Console.WriteLine(root); - -// String array content: -// Any collection other than a collection of XElement or XAttribute objects -// are converted to strings. The strings are concatenated and added. -string[] stringArray = { - "abc", - "def", - "ghi" -}; -root = new XElement("Root", stringArray); -Console.WriteLine(root); - -// XElement object array content: -XElement[] ellArray = { - new XElement("NewChild1", 1), - new XElement("NewChild2", 2), - new XElement("NewChild3", 3) -}; -root = new XElement("Root", ellArray); -Console.WriteLine(root); - -// XAttribute object array content: -XAttribute[] attArray = { - new XAttribute("NewAtt1", 1), - new XAttribute("NewAtt2", 2), - new XAttribute("NewAtt3", 3) -}; -root = new XElement("Root", attArray); -Console.WriteLine(root); -``` - -```vb -Dim root As XElement - -' String content: -root = Some text -Console.WriteLine(root) - -' XElement object content: -root = - n - -Console.WriteLine(root) - -' XAttribute object content: -root = -Console.WriteLine(root) - -' Double content: -Dim dbl As Double = 12.345 -root = <%= dbl %> -Console.WriteLine(root) - -' DateTime content: -Dim dt As DateTime = New DateTime(2006, 10, 6, 12, 30, 0) -root = <%= dt %> -Console.WriteLine(root) - -' String array content: -' Any collection other than a collection of XElement or XAttribute objects -' are converted to strings. The strings are concatenated and added. - -Dim stringArray As String() = { _ - "abc", _ - "def", _ - "ghi" _ -} -root = <%= stringArray %> -Console.WriteLine(root) - -' XElement object array content: -Dim ellArray As XElement() = { _ - 1, _ - 2, _ - 3 _ -} - -root = <%= ellArray %> -Console.WriteLine(root) - -' XAttribute object array content -Dim attArray As XAttribute() = { _ - New XAttribute("NewAtt1", 1), _ - New XAttribute("NewAtt2", 2), _ - New XAttribute("NewAtt3", 3) _ -} -root = <%= attArray %> -Console.WriteLine(root) -``` - - This example produces the following output: - + . Typical use of this constructor is to specify a string as the parameter instead of creating a new . + + When creating an element in a namespace, typical use is to use the addition operator overload with an and a string to create an . For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). + + For details about the valid content that can be passed to this constructor, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + + + +## Examples + The following example creates an XML tree. The content of the new element comes from a LINQ query. + +```csharp +XElement xmlTree1 = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5), + new XElement("Child6", 6) +); + +XElement xmlTree2 = new XElement("Root", + from el in xmlTree1.Elements() + where((int)el >= 3 && (int)el <= 5) + select el +); +Console.WriteLine(xmlTree2); +``` + +```vb +Dim xmlTree1 As XElement = _ + + 1 + 2 + 3 + 4 + 5 + 6 + + +Dim xmlTree2 As XElement = _ + + <%= From el In xmlTree1.Elements() _ + Where el.Value >= 3 And el.Value <= 5 _ + Select el %> + + +Console.WriteLine(xmlTree2) +``` + + This example produces the following output: + ```xml -Some text - - n - - -12.345 -2006-10-06T12:30:00 -abcdefghi - - 1 - 2 - 3 - - -``` - - The following example creates an XML tree in a namespace. - -```csharp -// Create an XML tree in a namespace. -XNamespace aw = "http://www.adventure-works.com"; -XElement root = new XElement(aw + "Root", - new XElement(aw + "Child", "child content") -); -Console.WriteLine(root); -``` - -```vb -' Create an XML tree in a namespace. -Dim root As XElement = _ - - child content - -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - - child content - -``` - - The following example creates an XML tree with nested namespaces. - -```csharp -// Create an XML tree with nested namespaces. -XNamespace aw = "http://www.adventure-works.com"; -XNamespace fc = "www.fourthcoffee.com"; -XElement root = new XElement(aw + "Root", - new XElement(fc + "Child", - new XElement(aw + "DifferentChild", "other content") - ) -); -Console.WriteLine(root); -``` - -```vb -' Create an XML tree with nested namespaces. -Dim root As XDocument = _ - - - - other content - - -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - - - other content - - -``` - + + 3 + 4 + 5 + +``` + + The following example creates an XML tree with a variety of types of content. + +```csharp +XElement root; + +// String content: +root = new XElement("Root", "Some text"); +Console.WriteLine(root); + +// XElement object content: +root = new XElement("Root", + new XElement("NewChild", "n") +); +Console.WriteLine(root); + +// XAttribute object content: +root = new XElement("Root", + new XAttribute("NewAttribute", "n") +); +Console.WriteLine(root); + +// Double content: +double dbl = 12.345; +root = new XElement("Root", dbl); +Console.WriteLine(root); + +// DateTime content: +DateTime dt = new DateTime(2006, 10, 6, 12, 30, 00); +root = new XElement("Root", dt); +Console.WriteLine(root); + +// String array content: +// Any collection other than a collection of XElement or XAttribute objects +// are converted to strings. The strings are concatenated and added. +string[] stringArray = { + "abc", + "def", + "ghi" +}; +root = new XElement("Root", stringArray); +Console.WriteLine(root); + +// XElement object array content: +XElement[] ellArray = { + new XElement("NewChild1", 1), + new XElement("NewChild2", 2), + new XElement("NewChild3", 3) +}; +root = new XElement("Root", ellArray); +Console.WriteLine(root); + +// XAttribute object array content: +XAttribute[] attArray = { + new XAttribute("NewAtt1", 1), + new XAttribute("NewAtt2", 2), + new XAttribute("NewAtt3", 3) +}; +root = new XElement("Root", attArray); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement + +' String content: +root = Some text +Console.WriteLine(root) + +' XElement object content: +root = + n + +Console.WriteLine(root) + +' XAttribute object content: +root = +Console.WriteLine(root) + +' Double content: +Dim dbl As Double = 12.345 +root = <%= dbl %> +Console.WriteLine(root) + +' DateTime content: +Dim dt As DateTime = New DateTime(2006, 10, 6, 12, 30, 0) +root = <%= dt %> +Console.WriteLine(root) + +' String array content: +' Any collection other than a collection of XElement or XAttribute objects +' are converted to strings. The strings are concatenated and added. + +Dim stringArray As String() = { _ + "abc", _ + "def", _ + "ghi" _ +} +root = <%= stringArray %> +Console.WriteLine(root) + +' XElement object array content: +Dim ellArray As XElement() = { _ + 1, _ + 2, _ + 3 _ +} + +root = <%= ellArray %> +Console.WriteLine(root) + +' XAttribute object array content +Dim attArray As XAttribute() = { _ + New XAttribute("NewAtt1", 1), _ + New XAttribute("NewAtt2", 2), _ + New XAttribute("NewAtt3", 3) _ +} +root = <%= attArray %> +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml +Some text + + n + + +12.345 +2006-10-06T12:30:00 +abcdefghi + + 1 + 2 + 3 + + +``` + + The following example creates an XML tree in a namespace. + +```csharp +// Create an XML tree in a namespace. +XNamespace aw = "http://www.adventure-works.com"; +XElement root = new XElement(aw + "Root", + new XElement(aw + "Child", "child content") +); +Console.WriteLine(root); +``` + +```vb +' Create an XML tree in a namespace. +Dim root As XElement = _ + + child content + +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + + child content + +``` + + The following example creates an XML tree with nested namespaces. + +```csharp +// Create an XML tree with nested namespaces. +XNamespace aw = "http://www.adventure-works.com"; +XNamespace fc = "www.fourthcoffee.com"; +XElement root = new XElement(aw + "Root", + new XElement(fc + "Child", + new XElement(aw + "DifferentChild", "other content") + ) +); +Console.WriteLine(root); +``` + +```vb +' Create an XML tree with nested namespaces. +Dim root As XDocument = _ + + + + other content + + +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + + + other content + + +``` + ]]> LINQ to XML overview @@ -1232,13 +1232,13 @@ Console.WriteLine(root) Returns a collection of elements that contain this element, and the ancestors of this element. - @@ -1283,59 +1283,59 @@ Console.WriteLine(root) Returns a collection of elements that contain this element, and the ancestors of this element. An of of elements that contain this element, and the ancestors of this element. - aas = - from el in gc.AncestorsAndSelf() - select el; -foreach (XElement el in aas) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - - - element content - - - -Dim GC As XElement = xmlTree..(0) - -Dim aas As IEnumerable(Of XElement) = _ - From el In GC.AncestorsAndSelf() _ - Select el - -For Each el In aas - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -GrandChild -Child -Root -``` - + aas = + from el in gc.AncestorsAndSelf() + select el; +foreach (XElement el in aas) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + + + element content + + + +Dim GC As XElement = xmlTree..(0) + +Dim aas As IEnumerable(Of XElement) = _ + From el In GC.AncestorsAndSelf() _ + Select el + +For Each el In aas + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +GrandChild +Child +Root +``` + ]]> @@ -1384,51 +1384,51 @@ Root Returns a filtered collection of elements that contain this element, and the ancestors of this element. Only elements that have a matching are included in the collection. An of that contain this element, and the ancestors of this element. Only elements that have a matching are included in the collection. - aas = gc.AncestorsAndSelf("Child"); -foreach (XElement el in aas) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - - - element content - - - -Dim GC As XElement = xmlTree..(0) -Dim aas As IEnumerable(Of XElement) = GC.AncestorsAndSelf("Child") -For Each el In aas - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -Child -``` - + aas = gc.AncestorsAndSelf("Child"); +foreach (XElement el in aas) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + + + element content + + + +Dim GC As XElement = xmlTree..(0) +Dim aas As IEnumerable(Of XElement) = GC.AncestorsAndSelf("Child") +For Each el In aas + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +Child +``` + ]]> @@ -1477,70 +1477,70 @@ Child Returns the of this that has the specified . An that has the specified ; if there is no attribute with the specified name. - - -Dim att As XAttribute = xmlTree.Attribute("Att") -Console.WriteLine(att) -``` - - This example produces the following output: - -``` -Att="attribute content" -``` - - The following is the same example, but in this case the XML is in a namespace. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). - -```csharp -XNamespace aw = "http://www.adventure-works.com"; -XElement xmlTree = new XElement(aw + "Root", - new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"), - new XAttribute(aw + "Att", "attribute content") -); -XAttribute att = xmlTree.Attribute(aw + "Att"); -Console.WriteLine(att); -``` - -```vb -Imports - -Module Module1 - Sub Main() - Dim xmlTree As XElement = - - Dim att As XAttribute = xmlTree.Attribute(GetXmlNamespace(aw) + "Att") - Console.WriteLine(att) - End Sub -End Module -``` - - This example produces the following output: - -``` -aw:Att="attribute content" -``` - + + +Dim att As XAttribute = xmlTree.Attribute("Att") +Console.WriteLine(att) +``` + + This example produces the following output: + +``` +Att="attribute content" +``` + + The following is the same example, but in this case the XML is in a namespace. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). + +```csharp +XNamespace aw = "http://www.adventure-works.com"; +XElement xmlTree = new XElement(aw + "Root", + new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"), + new XAttribute(aw + "Att", "attribute content") +); +XAttribute att = xmlTree.Attribute(aw + "Att"); +Console.WriteLine(att); +``` + +```vb +Imports + +Module Module1 + Sub Main() + Dim xmlTree As XElement = + + Dim att As XAttribute = xmlTree.Attribute(GetXmlNamespace(aw) + "Att") + Console.WriteLine(att) + End Sub +End Module +``` + + This example produces the following output: + +``` +aw:Att="attribute content" +``` + ]]> LINQ to XML overview @@ -1555,11 +1555,11 @@ aw:Att="attribute content" Returns a collection of attributes of this element. - LINQ to XML overview @@ -1609,91 +1609,91 @@ aw:Att="attribute content" Returns a collection of attributes of this element. An of of attributes of this element. - attList = - from at in xmlTree.Attributes() - select at; -foreach (XAttribute att in attList) - Console.WriteLine(att); -``` - -```vb -Dim xmlTree As XElement = - -Dim attList As IEnumerable(Of XAttribute) = _ -From at In xmlTree.Attributes() _ -Select at - -For Each att In attList - Console.WriteLine(att) -Next -``` - - This example produces the following output: - -``` -Att1="content1" -Att2="content2" -``` - - The following is the same example, but in this case the XML is in a namespace. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). - -```csharp -XNamespace aw = "http://www.adventure-works.com"; -XElement xmlTree = new XElement(aw + "Root", - new XAttribute(aw + "Att1", "content1"), - new XAttribute(aw + "Att2", "content2"), - new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com") -); -IEnumerable attList = - from at in xmlTree.Attributes() - select at; -foreach (XAttribute att in attList) - Console.WriteLine(att); -``` - -```vb -Imports - -Module Module1 - Sub Main() - Dim xmlTree As XElement = - - Dim attList As IEnumerable(Of XAttribute) = _ - From at In xmlTree.Attributes() _ - Select at - - For Each att In attList - Console.WriteLine(att) - Next - End Sub -End Module -``` - - This example produces the following output: - -``` -aw:Att1="content1" -aw:Att2="content2" -xmlns:aw="http://www.adventure-works.com" -``` - + attList = + from at in xmlTree.Attributes() + select at; +foreach (XAttribute att in attList) + Console.WriteLine(att); +``` + +```vb +Dim xmlTree As XElement = + +Dim attList As IEnumerable(Of XAttribute) = _ +From at In xmlTree.Attributes() _ +Select at + +For Each att In attList + Console.WriteLine(att) +Next +``` + + This example produces the following output: + +``` +Att1="content1" +Att2="content2" +``` + + The following is the same example, but in this case the XML is in a namespace. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). + +```csharp +XNamespace aw = "http://www.adventure-works.com"; +XElement xmlTree = new XElement(aw + "Root", + new XAttribute(aw + "Att1", "content1"), + new XAttribute(aw + "Att2", "content2"), + new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com") +); +IEnumerable attList = + from at in xmlTree.Attributes() + select at; +foreach (XAttribute att in attList) + Console.WriteLine(att); +``` + +```vb +Imports + +Module Module1 + Sub Main() + Dim xmlTree As XElement = + + Dim attList As IEnumerable(Of XAttribute) = _ + From at In xmlTree.Attributes() _ + Select at + + For Each att In attList + Console.WriteLine(att) + Next + End Sub +End Module +``` + + This example produces the following output: + +``` +aw:Att1="content1" +aw:Att2="content2" +xmlns:aw="http://www.adventure-works.com" +``` + ]]> @@ -1742,80 +1742,80 @@ xmlns:aw="http://www.adventure-works.com" Returns a filtered collection of attributes of this element. Only attributes that have a matching are included in the collection. An of that contains the attributes of this element. Only attributes that have a matching are included in the collection. - attList = xmlTree.Attributes("Att1"); -foreach (XAttribute att in attList) - Console.WriteLine(att); -``` - -```vb -Dim xmlTree As XElement = - -Dim attList As IEnumerable(Of XAttribute) = xmlTree.Attributes("Att1") - -For Each att In attList - Console.WriteLine(att) -Next -``` - - This example produces the following output: - -``` -Att1="content1" -``` - - The following is the same example, but in this case the XML is in a namespace. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). - -```csharp -XNamespace aw = "http://www.adventure-works.com"; -XElement xmlTree = new XElement(aw + "Root", - new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"), - new XAttribute(aw + "Att1", "content1"), - new XAttribute(aw + "Att2", "content2") -); -IEnumerable attList = xmlTree.Attributes(aw + "Att1"); -foreach (XAttribute att in attList) - Console.WriteLine(att); -``` - -```vb -Imports - -Module Module1 - Sub Main() - Dim xmlTree As XElement = - - Dim attList As IEnumerable(Of XAttribute) = xmlTree.Attributes(GetXmlNamespace(aw) + "Att1") - - For Each att In attList - Console.WriteLine(att) - Next - End Sub -End Module -``` - - This example produces the following output: - -``` -aw:Att1="content1" -``` - + attList = xmlTree.Attributes("Att1"); +foreach (XAttribute att in attList) + Console.WriteLine(att); +``` + +```vb +Dim xmlTree As XElement = + +Dim attList As IEnumerable(Of XAttribute) = xmlTree.Attributes("Att1") + +For Each att In attList + Console.WriteLine(att) +Next +``` + + This example produces the following output: + +``` +Att1="content1" +``` + + The following is the same example, but in this case the XML is in a namespace. For more information, see [Work with XML Namespaces](/dotnet/standard/linq/namespaces-overview). + +```csharp +XNamespace aw = "http://www.adventure-works.com"; +XElement xmlTree = new XElement(aw + "Root", + new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"), + new XAttribute(aw + "Att1", "content1"), + new XAttribute(aw + "Att2", "content2") +); +IEnumerable attList = xmlTree.Attributes(aw + "Att1"); +foreach (XAttribute att in attList) + Console.WriteLine(att); +``` + +```vb +Imports + +Module Module1 + Sub Main() + Dim xmlTree As XElement = + + Dim attList As IEnumerable(Of XAttribute) = xmlTree.Attributes(GetXmlNamespace(aw) + "Att1") + + For Each att In attList + Console.WriteLine(att) + Next + End Sub +End Module +``` + + This example produces the following output: + +``` +aw:Att1="content1" +``` + ]]> LINQ to XML overview @@ -1859,67 +1859,67 @@ aw:Att1="content1" Returns a collection of nodes that contain this element, and all descendant nodes of this element, in document order. An of that contain this element, and all descendant nodes of this element, in document order. - dnas = - from node in xmlTree.DescendantNodesAndSelf() - select node; -foreach (XNode node in dnas) -{ - if (node is XElement) - Console.WriteLine((node as XElement).Name); - else - Console.WriteLine(node); -} -``` - -```vb -Dim xmlTree As XElement = _ - - Some textelement content - - - -Dim dnas As IEnumerable(Of XNode) = _ - From node In xmlTree.DescendantNodesAndSelf() _ - Select node - -For Each node In dnas - If TypeOf node Is XElement Then - Console.WriteLine(DirectCast(node, XElement).Name) - Else - Console.WriteLine(node) - End If -Next -``` - - This example produces the following output: - -``` -Root -Child -Some text -GrandChild -element content -``` - + dnas = + from node in xmlTree.DescendantNodesAndSelf() + select node; +foreach (XNode node in dnas) +{ + if (node is XElement) + Console.WriteLine((node as XElement).Name); + else + Console.WriteLine(node); +} +``` + +```vb +Dim xmlTree As XElement = _ + + Some textelement content + + + +Dim dnas As IEnumerable(Of XNode) = _ + From node In xmlTree.DescendantNodesAndSelf() _ + Select node + +For Each node In dnas + If TypeOf node Is XElement Then + Console.WriteLine(DirectCast(node, XElement).Name) + Else + Console.WriteLine(node) + End If +Next +``` + + This example produces the following output: + +``` +Root +Child +Some text +GrandChild +element content +``` + ]]> LINQ to XML overview @@ -1934,11 +1934,11 @@ element content Returns a collection of elements that contain this element, and all descendant elements of this element, in document order. - LINQ to XML overview @@ -1982,56 +1982,56 @@ element content Returns a collection of elements that contain this element, and all descendant elements of this element, in document order. An of of elements that contain this element, and all descendant elements of this element, in document order. - das = - from el in xmlTree.DescendantsAndSelf() - select el; -foreach (XElement el in das) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - - Some text - element content - - - -Dim das As IEnumerable(Of XElement) = _ - From el In xmlTree.DescendantsAndSelf() _ - Select el - -For Each el In das - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -Root -Child -GrandChild -``` - + das = + from el in xmlTree.DescendantsAndSelf() + select el; +foreach (XElement el in das) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + + Some text + element content + + + +Dim das As IEnumerable(Of XElement) = _ + From el In xmlTree.DescendantsAndSelf() _ + Select el + +For Each el In das + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +Root +Child +GrandChild +``` + ]]> LINQ to XML overview @@ -2079,50 +2079,50 @@ GrandChild Returns a filtered collection of elements that contain this element, and all descendant elements of this element, in document order. Only elements that have a matching are included in the collection. An of that contain this element, and all descendant elements of this element, in document order. Only elements that have a matching are included in the collection. - das = xmlTree.DescendantsAndSelf("Child"); -foreach (XElement el in das) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - - Some text - element content - - - -Dim das As IEnumerable(Of XElement) = xmlTree.DescendantsAndSelf("Child") - -For Each el In das - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -Child -``` - + das = xmlTree.DescendantsAndSelf("Child"); +foreach (XElement el in das) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + + Some text + element content + + + +Dim das As IEnumerable(Of XElement) = xmlTree.DescendantsAndSelf("Child") + +For Each el In das + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +Child +``` + ]]> LINQ to XML overview @@ -2165,11 +2165,11 @@ Child Gets an empty collection of elements. An of that contains an empty collection. - objects. - + objects. + ]]> LINQ to XML overview @@ -2213,36 +2213,36 @@ Child Gets the first attribute of this element. An that contains the first attribute of this element. - -Console.WriteLine(xmlTree.FirstAttribute) -``` - - This example produces the following output: - -``` -Att1="1" -``` - + +Console.WriteLine(xmlTree.FirstAttribute) +``` + + This example produces the following output: + +``` +Att1="1" +``` + ]]> LINQ to XML overview @@ -2286,45 +2286,45 @@ Att1="1" Gets the default of this . An that contains the default namespace of this . - for the default namespace. - - If there is no attribute that declares the default namespace, then this method returns . - - When creating XML trees using C#, even if an XML tree would be serialized with a default namespace, if the namespace is not persisted in the XML tree as an attribute, this method will not report the namespace as the default namespace. - - When creating XML trees using Visual Basic and XML literals, if you create the XML in a default namespace using the Imports statement, then a namespace attribute will be created in the tree by the Visual Basic compiler, and this method will report that namespace. - - - -## Examples - The following example creates an XML tree that has a default namespace. It then uses this method to retrieve the default namespace. - -```csharp -String xml = ""; -XElement e = XElement.Parse(xml); -Console.WriteLine("Default namespace: {0}", e.GetDefaultNamespace()); -``` - -```vb -Imports - -Module Module1 - Sub Main() - Dim e As XElement = - Console.WriteLine("Default namespace: {0}", e.GetDefaultNamespace()) - End Sub -End Module -``` - - This example produces the following output: - -``` -Default namespace: http://www.adventure-works.com -``` - + for the default namespace. + + If there is no attribute that declares the default namespace, then this method returns . + + When creating XML trees using C#, even if an XML tree would be serialized with a default namespace, if the namespace is not persisted in the XML tree as an attribute, this method will not report the namespace as the default namespace. + + When creating XML trees using Visual Basic and XML literals, if you create the XML in a default namespace using the Imports statement, then a namespace attribute will be created in the tree by the Visual Basic compiler, and this method will report that namespace. + + + +## Examples + The following example creates an XML tree that has a default namespace. It then uses this method to retrieve the default namespace. + +```csharp +String xml = ""; +XElement e = XElement.Parse(xml); +Console.WriteLine("Default namespace: {0}", e.GetDefaultNamespace()); +``` + +```vb +Imports + +Module Module1 + Sub Main() + Dim e As XElement = + Console.WriteLine("Default namespace: {0}", e.GetDefaultNamespace()) + End Sub +End Module +``` + + This example produces the following output: + +``` +Default namespace: http://www.adventure-works.com +``` + ]]> LINQ to XML overview @@ -2372,42 +2372,42 @@ Default namespace: http://www.adventure-works.com Gets the namespace associated with a particular prefix for this . An for the namespace associated with the prefix for this . - for the prefix. - -```csharp -XElement xmlTree = XElement.Parse(""); -XNamespace awNamespace = xmlTree.GetNamespaceOfPrefix("aw"); -Console.WriteLine("Namespace: {0}", awNamespace); -``` - - When using Visual Basic, you would typically use the [GetXmlNamespace Operator](/dotnet/visual-basic/language-reference/operators/getxmlnamespace-operator) operator, as follows - -```vb -Imports - -Module Module1 - Sub Main() - Dim xmlTree As XElement = - Dim awNamespace As XNamespace = GetXmlNamespace(aw) - Console.WriteLine("Namespace: {0}", awNamespace) - End Sub -End Module -``` - - This example produces the following output: - -``` -Namespace: http://www.adventure-works.com -``` - + for the prefix. + +```csharp +XElement xmlTree = XElement.Parse(""); +XNamespace awNamespace = xmlTree.GetNamespaceOfPrefix("aw"); +Console.WriteLine("Namespace: {0}", awNamespace); +``` + + When using Visual Basic, you would typically use the [GetXmlNamespace Operator](/dotnet/visual-basic/language-reference/operators/getxmlnamespace-operator) operator, as follows + +```vb +Imports + +Module Module1 + Sub Main() + Dim xmlTree As XElement = + Dim awNamespace As XNamespace = GetXmlNamespace(aw) + Console.WriteLine("Namespace: {0}", awNamespace) + End Sub +End Module +``` + + This example produces the following output: + +``` +Namespace: http://www.adventure-works.com +``` + ]]> LINQ to XML overview @@ -2455,42 +2455,42 @@ Namespace: http://www.adventure-works.com Gets the prefix associated with a namespace for this . A that contains the namespace prefix. - when calling this method. - -```csharp -XElement xmlTree = XElement.Parse(""); -string prefix = xmlTree.GetPrefixOfNamespace("http://www.adventure-works.com"); -Console.WriteLine("Prefix: {0}", prefix); -``` - -```vb -Imports - -Module Module1 - Sub Main() - Dim xmlTree As XElement = - Dim prefix As String = xmlTree.GetPrefixOfNamespace("http://www.adventure-works.com") - Console.WriteLine("Prefix: {0}", prefix) - End Sub -End Module -``` - - This example produces the following output: - -``` -Prefix: aw -``` - + when calling this method. + +```csharp +XElement xmlTree = XElement.Parse(""); +string prefix = xmlTree.GetPrefixOfNamespace("http://www.adventure-works.com"); +Console.WriteLine("Prefix: {0}", prefix); +``` + +```vb +Imports + +Module Module1 + Sub Main() + Dim xmlTree As XElement = + Dim prefix As String = xmlTree.GetPrefixOfNamespace("http://www.adventure-works.com") + Console.WriteLine("Prefix: {0}", prefix) + End Sub +End Module +``` + + This example produces the following output: + +``` +Prefix: aw +``` + ]]> LINQ to XML overview @@ -2534,35 +2534,35 @@ Prefix: aw if this element has at least one attribute; otherwise . - -Console.WriteLine(xmlTree1.HasAttributes) - -Dim xmlTree2 As XElement = -Console.WriteLine(xmlTree2.HasAttributes) -``` - - This example produces the following output: - -``` -True -False -``` - + +Console.WriteLine(xmlTree1.HasAttributes) + +Dim xmlTree2 As XElement = +Console.WriteLine(xmlTree2.HasAttributes) +``` + + This example produces the following output: + +``` +True +False +``` + ]]> LINQ to XML overview @@ -2606,38 +2606,38 @@ False if this element has at least one child element; otherwise . - - 1 - -Console.WriteLine(xmlTree1.HasElements) - -Dim xmlTree2 As XElement = contents -Console.WriteLine(xmlTree2.HasElements) -``` - - This example produces the following output: - -``` -True -False -``` - + + 1 + +Console.WriteLine(xmlTree1.HasElements) + +Dim xmlTree2 As XElement = contents +Console.WriteLine(xmlTree2.HasElements) +``` + + This example produces the following output: + +``` +True +False +``` + ]]> LINQ to XML overview @@ -2681,68 +2681,68 @@ False if this element contains no content; otherwise . - -Console.WriteLine(el1) -Console.WriteLine(el1.IsEmpty) -Console.WriteLine() -Dim el2 As XElement = content -Console.WriteLine(el2) -Console.WriteLine(el2.IsEmpty) -Console.WriteLine() -Dim el3 As XElement = -Console.WriteLine(el3) -Console.WriteLine(el3.IsEmpty) -Console.WriteLine() -el3.ReplaceAll(Nothing) -Console.WriteLine(el3) -Console.WriteLine(el3.IsEmpty) -``` - - This example produces the following output: - -``` - -True - -content -False - - -False - - -True -``` - + +Console.WriteLine(el1) +Console.WriteLine(el1.IsEmpty) +Console.WriteLine() +Dim el2 As XElement = content +Console.WriteLine(el2) +Console.WriteLine(el2.IsEmpty) +Console.WriteLine() +Dim el3 As XElement = +Console.WriteLine(el3) +Console.WriteLine(el3.IsEmpty) +Console.WriteLine() +el3.ReplaceAll(Nothing) +Console.WriteLine(el3) +Console.WriteLine(el3.IsEmpty) +``` + + This example produces the following output: + +``` + +True + +content +False + + +False + + +True +``` + ]]> LINQ to XML overview @@ -2792,36 +2792,36 @@ True Gets the last attribute of this element. An that contains the last attribute of this element. - -Console.WriteLine(xmlTree.LastAttribute) -``` - - This example produces the following output: - -``` -Att3="3" -``` - + +Console.WriteLine(xmlTree.LastAttribute) +``` + + This example produces the following output: + +``` +Att3="3" +``` + ]]> LINQ to XML overview @@ -2836,13 +2836,13 @@ Att3="3" Creates a new from a file specified by a URI, from an , or from an . - from a file, a , or an . - - To create an from a string that contains XML, use . - + from a file, a , or an . + + To create an from a string that contains XML, use . + ]]> @@ -2896,19 +2896,19 @@ Att3="3" Creates a new instance by using the specified stream. An object used to read the data that is contained in the stream. - overload that takes as a parameter. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - If you have to modify , following these steps: - -1. Create an by calling one of the overloads that take as a parameter. - -2. Pass the to one of the 's overloads that takes as a parameter. - + overload that takes as a parameter. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + If you have to modify , following these steps: + +1. Create an by calling one of the overloads that take as a parameter. + +2. Pass the to one of the 's overloads that takes as a parameter. + ]]> @@ -2960,40 +2960,40 @@ Att3="3" Loads an from a . An that contains the XML that was read from the specified . - . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example loads an element from a . - -```csharp -TextReader sr = new StringReader(""); -XElement xmlTree = XElement.Load(sr); -sr.Close(); -Console.WriteLine(xmlTree); -``` - -```vb -Dim sr As TextReader = New StringReader("") -Dim xmlTree As XElement = XElement.Load(sr) -sr.Close() -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - - -``` - + . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example loads an element from a . + +```csharp +TextReader sr = new StringReader(""); +XElement xmlTree = XElement.Load(sr); +sr.Close(); +Console.WriteLine(xmlTree); +``` + +```vb +Dim sr As TextReader = New StringReader("") +Dim xmlTree As XElement = XElement.Load(sr) +sr.Close() +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + + +``` + ]]> LINQ to XML overview @@ -3053,45 +3053,45 @@ Console.WriteLine(xmlTree) Loads an from a file. An that contains the contents of the specified file. - . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example creates an XML tree, saves it to a file, and then uses this method to load the from the file. - -```csharp -XElement xmlTree1 = new XElement("Root", - new XElement("Child", "content") -); -xmlTree1.Save("Tree.xml"); - -XElement xmlTree2 = XElement.Load("Tree.xml"); -Console.WriteLine(xmlTree2.Name); -``` - -```vb -Dim xmlTree1 As XElement = _ - - Content - -xmlTree1.Save("Tree.xml") - -Dim xmlTree2 As XElement = XElement.Load("Tree.xml") -Console.WriteLine(xmlTree2.Name) -``` - - This example produces the following output: - -``` -Root -``` - + . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example creates an XML tree, saves it to a file, and then uses this method to load the from the file. + +```csharp +XElement xmlTree1 = new XElement("Root", + new XElement("Child", "content") +); +xmlTree1.Save("Tree.xml"); + +XElement xmlTree2 = XElement.Load("Tree.xml"); +Console.WriteLine(xmlTree2.Name); +``` + +```vb +Dim xmlTree1 As XElement = _ + + Content + +xmlTree1.Save("Tree.xml") + +Dim xmlTree2 As XElement = XElement.Load("Tree.xml") +Console.WriteLine(xmlTree2.Name) +``` + + This example produces the following output: + +``` +Root +``` + ]]> @@ -3146,66 +3146,66 @@ Root Loads an from an . An that contains the XML that was read from the specified . - from a DOM document, and then using the to create an , this method can be used to create a copy of a DOM document in a LINQ to XML tree. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example creates a DOM document, creates an from the DOM document, instantiates a tree from the reader. This code effectively copies a DOM document into a LINQ to XML tree. - -```csharp -// Create a DOM document with some content. -XmlDocument doc = new XmlDocument(); -XmlElement child = doc.CreateElement("Child"); -child.InnerText = "child contents"; -XmlElement root = doc.CreateElement("Root"); -root.AppendChild(child); -doc.AppendChild(root); - -// Create a reader and move to the content. -using (XmlNodeReader nodeReader = new XmlNodeReader(doc)) { - // the reader must be in the Interactive state in order to - // Create a LINQ to XML tree from it. - nodeReader.MoveToContent(); - - XElement xRoot = XElement.Load(nodeReader); - Console.WriteLine(xRoot); -} -``` - -```vb -' Create a DOM document with some content. -Dim doc As XmlDocument = New XmlDocument() -Dim child As XmlElement = doc.CreateElement("Child") -child.InnerText = "child contents" -Dim root As XmlElement = doc.CreateElement("Root") -root.AppendChild(child) -doc.AppendChild(root) - -' Create a reader and move to the content. -Using nodeReader = New XmlNodeReader(doc) - ' the reader must be in the Interactive state in order to - ' Create a LINQ to XML tree from it. - nodeReader.MoveToContent() - - Dim xRoot As XElement = XElement.Load(nodeReader) - Console.WriteLine(xRoot) -End Using -``` - - This example produces the following output: - -```xml - - child contents - -``` - + from a DOM document, and then using the to create an , this method can be used to create a copy of a DOM document in a LINQ to XML tree. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example creates a DOM document, creates an from the DOM document, instantiates a tree from the reader. This code effectively copies a DOM document into a LINQ to XML tree. + +```csharp +// Create a DOM document with some content. +XmlDocument doc = new XmlDocument(); +XmlElement child = doc.CreateElement("Child"); +child.InnerText = "child contents"; +XmlElement root = doc.CreateElement("Root"); +root.AppendChild(child); +doc.AppendChild(root); + +// Create a reader and move to the content. +using (XmlNodeReader nodeReader = new XmlNodeReader(doc)) { + // the reader must be in the Interactive state in order to + // Create a LINQ to XML tree from it. + nodeReader.MoveToContent(); + + XElement xRoot = XElement.Load(nodeReader); + Console.WriteLine(xRoot); +} +``` + +```vb +' Create a DOM document with some content. +Dim doc As XmlDocument = New XmlDocument() +Dim child As XmlElement = doc.CreateElement("Child") +child.InnerText = "child contents" +Dim root As XmlElement = doc.CreateElement("Root") +root.AppendChild(child) +doc.AppendChild(root) + +' Create a reader and move to the content. +Using nodeReader = New XmlNodeReader(doc) + ' the reader must be in the Interactive state in order to + ' Create a LINQ to XML tree from it. + nodeReader.MoveToContent() + + Dim xRoot As XElement = XElement.Load(nodeReader) + Console.WriteLine(xRoot) +End Using +``` + + This example produces the following output: + +```xml + + child contents + +``` + ]]> LINQ to XML overview @@ -3253,17 +3253,17 @@ End Using Creates a new instance by using the specified stream, optionally preserving white space, setting the base URI, and retaining line information. An object used to read the data that the stream contains. - . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - If you have to modify , following these steps: - -1. Create an by calling one of the overloads that take as a parameter. - -2. Pass the to one of the 's overloads that takes as a parameter. - + . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + If you have to modify , following these steps: + +1. Create an by calling one of the overloads that take as a parameter. + +2. Pass the to one of the 's overloads that takes as a parameter. + ]]> @@ -3311,152 +3311,152 @@ End Using Loads an from a , optionally preserving white space and retaining line information. An that contains the XML that was read from the specified . - flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. - - If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. - - If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - Use to create an from a string that contains XML. - - Setting will have no effect when loading from a . - - There is a performance penalty if you set the flag. - - The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example loads an from a in two different ways: preserving white space, and not preserving white space. It then uses a query to determine the number of white space nodes in the resulting XML tree. - -```csharp -TextReader sr; -int whiteSpaceNodes; - -sr = new StringReader(" "); -XElement xmlTree1 = XElement.Load(sr, LoadOptions.None); -sr.Close(); -whiteSpaceNodes = xmlTree1 - .DescendantNodesAndSelf() - .OfType() - .Where(tNode => tNode.ToString().Trim().Length == 0) - .Count(); -Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes); - -sr = new StringReader(" "); -XElement xmlTree2 = XElement.Load(sr, LoadOptions.PreserveWhitespace); -sr.Close(); -whiteSpaceNodes = xmlTree2 - .DescendantNodesAndSelf() - .OfType() - .Where(tNode => tNode.ToString().Trim().Length == 0) - .Count(); -Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes); -``` - -```vb -Dim sr As TextReader -Dim whiteSpaceNodes As Integer - -sr = New StringReader(" ") -Dim xmlTree1 As XElement = XElement.Load(sr, LoadOptions.None) -sr.Close() -whiteSpaceNodes = xmlTree1 _ - .DescendantNodesAndSelf() _ - .OfType(Of XText)() _ - .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ - .Count() -Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes) - -sr = New StringReader(" ") -Dim xmlTree2 As XElement = XElement.Load(sr, LoadOptions.PreserveWhitespace) -sr.Close() -whiteSpaceNodes = xmlTree2 _ - .DescendantNodesAndSelf() _ - .OfType(Of XText)() _ - .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ - .Count() -Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes) -``` - - This example produces the following output: - -``` -Count of white space nodes (not preserving whitespace): 0 -Count of white space nodes (preserving whitespace): 3 -``` - - The following example loads the line information as it loads from the . It then prints the line information. - -```csharp -TextReader sr = new StringReader( -@" - - - - -"); -XElement po = XElement.Load(sr, - LoadOptions.SetLineInfo); -Console.WriteLine("{0}{1}{2}", - "Element Name".PadRight(20), - "Line".PadRight(5), - "Position"); -Console.WriteLine("{0}{1}{2}", - "------------".PadRight(20), - "----".PadRight(5), - "--------"); -foreach (XElement e in po.DescendantsAndSelf()) - Console.WriteLine("{0}{1}{2}", - ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), - ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), - ((IXmlLineInfo)e).LinePosition); -``` - -```vb -Dim sr As TextReader = New StringReader( _ - "" & Environment.NewLine & _ - " " & Environment.NewLine & _ - " " & Environment.NewLine & _ - " " & Environment.NewLine & _ - " " & Environment.NewLine & _ - "") -Dim po As XElement = XElement.Load(sr, LoadOptions.SetLineInfo) -Console.WriteLine("{0}{1}{2}", _ - "Element Name".PadRight(20), _ - "Line".PadRight(5), _ - "Position") -Console.WriteLine("{0}{1}{2}", _ - "------------".PadRight(20), _ - "----".PadRight(5), _ - "--------") -For Each e As XElement In po.DescendantsAndSelf() - Console.WriteLine("{0}{1}{2}", _ - ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString).PadRight(20), _ - (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _ - (DirectCast(e, IXmlLineInfo)).LinePosition) -Next -``` - - This example produces the following output: - -``` -Element Name Line Position ------------- ---- -------- -Root 1 2 - Child 2 4 - GrandChild1 3 6 - GrandChild2 4 6 -``` - + flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. + + If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. + + If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + Use to create an from a string that contains XML. + + Setting will have no effect when loading from a . + + There is a performance penalty if you set the flag. + + The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example loads an from a in two different ways: preserving white space, and not preserving white space. It then uses a query to determine the number of white space nodes in the resulting XML tree. + +```csharp +TextReader sr; +int whiteSpaceNodes; + +sr = new StringReader(" "); +XElement xmlTree1 = XElement.Load(sr, LoadOptions.None); +sr.Close(); +whiteSpaceNodes = xmlTree1 + .DescendantNodesAndSelf() + .OfType() + .Where(tNode => tNode.ToString().Trim().Length == 0) + .Count(); +Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes); + +sr = new StringReader(" "); +XElement xmlTree2 = XElement.Load(sr, LoadOptions.PreserveWhitespace); +sr.Close(); +whiteSpaceNodes = xmlTree2 + .DescendantNodesAndSelf() + .OfType() + .Where(tNode => tNode.ToString().Trim().Length == 0) + .Count(); +Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes); +``` + +```vb +Dim sr As TextReader +Dim whiteSpaceNodes As Integer + +sr = New StringReader(" ") +Dim xmlTree1 As XElement = XElement.Load(sr, LoadOptions.None) +sr.Close() +whiteSpaceNodes = xmlTree1 _ + .DescendantNodesAndSelf() _ + .OfType(Of XText)() _ + .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ + .Count() +Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes) + +sr = New StringReader(" ") +Dim xmlTree2 As XElement = XElement.Load(sr, LoadOptions.PreserveWhitespace) +sr.Close() +whiteSpaceNodes = xmlTree2 _ + .DescendantNodesAndSelf() _ + .OfType(Of XText)() _ + .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ + .Count() +Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes) +``` + + This example produces the following output: + +``` +Count of white space nodes (not preserving whitespace): 0 +Count of white space nodes (preserving whitespace): 3 +``` + + The following example loads the line information as it loads from the . It then prints the line information. + +```csharp +TextReader sr = new StringReader( +@" + + + + +"); +XElement po = XElement.Load(sr, + LoadOptions.SetLineInfo); +Console.WriteLine("{0}{1}{2}", + "Element Name".PadRight(20), + "Line".PadRight(5), + "Position"); +Console.WriteLine("{0}{1}{2}", + "------------".PadRight(20), + "----".PadRight(5), + "--------"); +foreach (XElement e in po.DescendantsAndSelf()) + Console.WriteLine("{0}{1}{2}", + ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), + ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), + ((IXmlLineInfo)e).LinePosition); +``` + +```vb +Dim sr As TextReader = New StringReader( _ + "" & Environment.NewLine & _ + " " & Environment.NewLine & _ + " " & Environment.NewLine & _ + " " & Environment.NewLine & _ + " " & Environment.NewLine & _ + "") +Dim po As XElement = XElement.Load(sr, LoadOptions.SetLineInfo) +Console.WriteLine("{0}{1}{2}", _ + "Element Name".PadRight(20), _ + "Line".PadRight(5), _ + "Position") +Console.WriteLine("{0}{1}{2}", _ + "------------".PadRight(20), _ + "----".PadRight(5), _ + "--------") +For Each e As XElement In po.DescendantsAndSelf() + Console.WriteLine("{0}{1}{2}", _ + ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString).PadRight(20), _ + (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _ + (DirectCast(e, IXmlLineInfo)).LinePosition) +Next +``` + + This example produces the following output: + +``` +Element Name Line Position +------------ ---- -------- +Root 1 2 + Child 2 4 + GrandChild1 3 6 + GrandChild2 4 6 +``` + ]]> LINQ to XML overview @@ -3512,168 +3512,168 @@ Root 1 2 Loads an from a file, optionally preserving white space, setting the base URI, and retaining line information. An that contains the contents of the specified file. - flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. - - If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. - - If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - Use to create an from a string that contains XML. - - There is a performance penalty if you set the and the flags. - - The base URI and the line information are accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the base URI and line information may become meaningless. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example loads an from a file in two different ways: preserving white space, and not preserving white space. It then uses a query to determine the number of white space nodes in the resulting XML tree. - -```csharp -XElement xmlTree1 = XElement.Parse(" ", LoadOptions.PreserveWhitespace); -xmlTree1.Save("Tree.xml"); -Console.WriteLine(xmlTree1); - -int whiteSpaceNodes; -XElement xmlTree2 = XElement.Load("Tree.xml", - LoadOptions.None); -whiteSpaceNodes = xmlTree2 - .DescendantNodesAndSelf() - .OfType() - .Where(tNode => tNode.ToString().Trim().Length == 0) - .Count(); -Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes); - -XElement xmlTree3 = XElement.Load("Tree.xml", - LoadOptions.PreserveWhitespace); -whiteSpaceNodes = xmlTree3 - .DescendantNodesAndSelf() - .OfType() - .Where(tNode => tNode.ToString().Trim().Length == 0) - .Count(); -Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes); -``` - -```vb -Dim xmlTree1 As XElement = XElement.Parse(" ", LoadOptions.PreserveWhitespace) -xmlTree1.Save("Tree.xml") -Console.WriteLine(xmlTree1) - -Dim whiteSpaceNodes As Integer -Dim xmlTree2 As XElement = XElement.Load("Tree.xml", LoadOptions.None) -whiteSpaceNodes = xmlTree2 _ - .DescendantNodesAndSelf() _ - .OfType(Of XText)() _ - .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ - .Count() -Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes) - -Dim xmlTree3 As XElement = XElement.Load("Tree.xml", LoadOptions.PreserveWhitespace) -whiteSpaceNodes = xmlTree3 _ - .DescendantNodesAndSelf() _ - .OfType(Of XText)() _ - .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ - .Count() -Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes) -``` - - This example produces the following output: - -``` - -Count of white space nodes (not preserving whitespace): 0 -Count of white space nodes (preserving whitespace): 3 -``` - - The following example loads the base URI and line information as it loads the file. It then prints the base URI and the line information. - - This example uses the following resource file: [Sample XML File: Typical Purchase Order (LINQ to XML)](/dotnet/standard/linq/sample-xml-file-typical-purchase-order). - -```csharp -XElement po = XElement.Load("PurchaseOrder.xml", - LoadOptions.SetBaseUri | LoadOptions.SetLineInfo); -string[] splitUri = po.BaseUri.Split('/'); -Console.WriteLine("BaseUri: {0}", splitUri[splitUri.Length - 1]); -Console.WriteLine(); -Console.WriteLine("{0}{1}{2}", - "Element Name".PadRight(20), - "Line".PadRight(5), - "Position"); -Console.WriteLine("{0}{1}{2}", - "------------".PadRight(20), - "----".PadRight(5), - "--------"); -foreach (XElement e in po.DescendantsAndSelf()) - Console.WriteLine("{0}{1}{2}", - ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), - ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), - ((IXmlLineInfo)e).LinePosition); -``` - -```vb -Dim po As XElement = XElement.Load("PurchaseOrder.xml", LoadOptions.SetBaseUri Or LoadOptions.SetLineInfo) -Dim splitUri() As String = po.BaseUri.Split("/") -Console.WriteLine("BaseUri: {0}", splitUri(splitUri.Length - 1)) -Console.WriteLine() -Console.WriteLine("{0}{1}{2}", _ - "Element Name".PadRight(20), _ - "Line".PadRight(5), _ - "Position") -Console.WriteLine("{0}{1}{2}", _ - "------------".PadRight(20), _ - "----".PadRight(5), _ - "--------") -For Each e As XElement In po.DescendantsAndSelf() - Console.WriteLine("{0}{1}{2}", _ - ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString()).PadRight(20), _ - (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _ - (DirectCast(e, IXmlLineInfo)).LinePosition) -Next -``` - - This example produces the following output: - -``` -BaseUri: PurchaseOrder.xml - -Element Name Line Position ------------- ---- -------- -PurchaseOrder 2 2 - Address 3 4 - Name 4 6 - Street 5 6 - City 6 6 - State 7 6 - Zip 8 6 - Country 9 6 - Address 11 4 - Name 12 6 - Street 13 6 - City 14 6 - State 15 6 - Zip 16 6 - Country 17 6 - DeliveryNotes 19 4 - Items 20 4 - Item 21 6 - ProductName 22 8 - Quantity 23 8 - USPrice 24 8 - Comment 25 8 - Item 27 6 - ProductName 28 8 - Quantity 29 8 - USPrice 30 8 - ShipDate 31 8 -``` - + flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. + + If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. + + If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + Use to create an from a string that contains XML. + + There is a performance penalty if you set the and the flags. + + The base URI and the line information are accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the base URI and line information may become meaningless. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example loads an from a file in two different ways: preserving white space, and not preserving white space. It then uses a query to determine the number of white space nodes in the resulting XML tree. + +```csharp +XElement xmlTree1 = XElement.Parse(" ", LoadOptions.PreserveWhitespace); +xmlTree1.Save("Tree.xml"); +Console.WriteLine(xmlTree1); + +int whiteSpaceNodes; +XElement xmlTree2 = XElement.Load("Tree.xml", + LoadOptions.None); +whiteSpaceNodes = xmlTree2 + .DescendantNodesAndSelf() + .OfType() + .Where(tNode => tNode.ToString().Trim().Length == 0) + .Count(); +Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes); + +XElement xmlTree3 = XElement.Load("Tree.xml", + LoadOptions.PreserveWhitespace); +whiteSpaceNodes = xmlTree3 + .DescendantNodesAndSelf() + .OfType() + .Where(tNode => tNode.ToString().Trim().Length == 0) + .Count(); +Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes); +``` + +```vb +Dim xmlTree1 As XElement = XElement.Parse(" ", LoadOptions.PreserveWhitespace) +xmlTree1.Save("Tree.xml") +Console.WriteLine(xmlTree1) + +Dim whiteSpaceNodes As Integer +Dim xmlTree2 As XElement = XElement.Load("Tree.xml", LoadOptions.None) +whiteSpaceNodes = xmlTree2 _ + .DescendantNodesAndSelf() _ + .OfType(Of XText)() _ + .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ + .Count() +Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes) + +Dim xmlTree3 As XElement = XElement.Load("Tree.xml", LoadOptions.PreserveWhitespace) +whiteSpaceNodes = xmlTree3 _ + .DescendantNodesAndSelf() _ + .OfType(Of XText)() _ + .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ + .Count() +Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes) +``` + + This example produces the following output: + +``` + +Count of white space nodes (not preserving whitespace): 0 +Count of white space nodes (preserving whitespace): 3 +``` + + The following example loads the base URI and line information as it loads the file. It then prints the base URI and the line information. + + This example uses the following resource file: [Sample XML File: Typical Purchase Order (LINQ to XML)](/dotnet/standard/linq/sample-xml-file-typical-purchase-order). + +```csharp +XElement po = XElement.Load("PurchaseOrder.xml", + LoadOptions.SetBaseUri | LoadOptions.SetLineInfo); +string[] splitUri = po.BaseUri.Split('/'); +Console.WriteLine("BaseUri: {0}", splitUri[splitUri.Length - 1]); +Console.WriteLine(); +Console.WriteLine("{0}{1}{2}", + "Element Name".PadRight(20), + "Line".PadRight(5), + "Position"); +Console.WriteLine("{0}{1}{2}", + "------------".PadRight(20), + "----".PadRight(5), + "--------"); +foreach (XElement e in po.DescendantsAndSelf()) + Console.WriteLine("{0}{1}{2}", + ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), + ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), + ((IXmlLineInfo)e).LinePosition); +``` + +```vb +Dim po As XElement = XElement.Load("PurchaseOrder.xml", LoadOptions.SetBaseUri Or LoadOptions.SetLineInfo) +Dim splitUri() As String = po.BaseUri.Split("/") +Console.WriteLine("BaseUri: {0}", splitUri(splitUri.Length - 1)) +Console.WriteLine() +Console.WriteLine("{0}{1}{2}", _ + "Element Name".PadRight(20), _ + "Line".PadRight(5), _ + "Position") +Console.WriteLine("{0}{1}{2}", _ + "------------".PadRight(20), _ + "----".PadRight(5), _ + "--------") +For Each e As XElement In po.DescendantsAndSelf() + Console.WriteLine("{0}{1}{2}", _ + ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString()).PadRight(20), _ + (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _ + (DirectCast(e, IXmlLineInfo)).LinePosition) +Next +``` + + This example produces the following output: + +``` +BaseUri: PurchaseOrder.xml + +Element Name Line Position +------------ ---- -------- +PurchaseOrder 2 2 + Address 3 4 + Name 4 6 + Street 5 6 + City 6 6 + State 7 6 + Zip 8 6 + Country 9 6 + Address 11 4 + Name 12 6 + Street 13 6 + City 14 6 + State 15 6 + Zip 16 6 + Country 17 6 + DeliveryNotes 19 4 + Items 20 4 + Item 21 6 + ProductName 22 8 + Quantity 23 8 + USPrice 24 8 + Comment 25 8 + Item 27 6 + ProductName 28 8 + Quantity 29 8 + USPrice 30 8 + ShipDate 31 8 +``` + ]]> LINQ to XML overview @@ -3722,105 +3722,105 @@ PurchaseOrder 2 2 Loads an from an , optionally preserving white space, setting the base URI, and retaining line information. An that contains the XML that was read from the specified . - from a DOM document, and then using the to create an , this method can be used to create a copy of a DOM document in a LINQ to XML tree. - - Use to create an from a string that contains XML. - - Setting is not valid when loading from a . The will be configured to either read whitespace or not. The LINQ to XML tree will be populated with the whitespace nodes that the reader surfaces. This will be the behavior regardless of whether is set or not. - - The may have a valid base URI or not. If you set , the base URI will be set in the XML tree from the base URI that is reported by the . - - The may have a valid line information or not. If you set , the line information will be set in the XML tree from the line information that is reported by the . - - There is a performance penalty if you set the flag. - - The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example loads the line information that it loads from the . It then prints the line information. - -```csharp -string markup = -@" - - - -"; - -// Create a reader and move to the content. -using (XmlReader nodeReader = XmlReader.Create(new StringReader(markup))) -{ - // the reader must be in the Interactive state in order to - // Create a LINQ to XML tree from it. - nodeReader.MoveToContent(); - - XElement xRoot = XElement.Load(nodeReader, LoadOptions.SetLineInfo); - Console.WriteLine("{0}{1}{2}", - "Element Name".PadRight(20), - "Line".PadRight(5), - "Position"); - Console.WriteLine("{0}{1}{2}", - "------------".PadRight(20), - "----".PadRight(5), - "--------"); - foreach (XElement e in xRoot.DescendantsAndSelf()) - Console.WriteLine("{0}{1}{2}", - ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), - ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), - ((IXmlLineInfo)e).LinePosition); -} -``` - -```vb -Dim markup As String = _ - "" & Environment.NewLine & _ - " " & Environment.NewLine & _ - " " & Environment.NewLine & _ - " " & Environment.NewLine & _ - "" - -' Create a reader and move to the content. -Using nodeReader As XmlReader = XmlReader.Create(New StringReader(markup)) - - ' the reader must be in the Interactive state in order to - ' Create a LINQ to XML tree from it. - nodeReader.MoveToContent() - - Dim xRoot As XElement = XElement.Load(nodeReader, LoadOptions.SetLineInfo) - Console.WriteLine("{0}{1}{2}", _ - "Element Name".PadRight(20), _ - "Line".PadRight(5), _ - "Position") - Console.WriteLine("{0}{1}{2}", _ - "------------".PadRight(20), _ - "----".PadRight(5), _ - "--------") - For Each e As XElement In xRoot.DescendantsAndSelf() - Console.WriteLine("{0}{1}{2}", _ - ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString).PadRight(20), _ - (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _ - (DirectCast(e, IXmlLineInfo)).LinePosition) - Next -End Using -``` - - This example produces the following output: - -``` -Element Name Line Position ------------- ---- -------- -Root 1 2 - Child 2 6 - GrandChild 3 10 -``` - + from a DOM document, and then using the to create an , this method can be used to create a copy of a DOM document in a LINQ to XML tree. + + Use to create an from a string that contains XML. + + Setting is not valid when loading from a . The will be configured to either read whitespace or not. The LINQ to XML tree will be populated with the whitespace nodes that the reader surfaces. This will be the behavior regardless of whether is set or not. + + The may have a valid base URI or not. If you set , the base URI will be set in the XML tree from the base URI that is reported by the . + + The may have a valid line information or not. If you set , the line information will be set in the XML tree from the line information that is reported by the . + + There is a performance penalty if you set the flag. + + The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example loads the line information that it loads from the . It then prints the line information. + +```csharp +string markup = +@" + + + +"; + +// Create a reader and move to the content. +using (XmlReader nodeReader = XmlReader.Create(new StringReader(markup))) +{ + // the reader must be in the Interactive state in order to + // Create a LINQ to XML tree from it. + nodeReader.MoveToContent(); + + XElement xRoot = XElement.Load(nodeReader, LoadOptions.SetLineInfo); + Console.WriteLine("{0}{1}{2}", + "Element Name".PadRight(20), + "Line".PadRight(5), + "Position"); + Console.WriteLine("{0}{1}{2}", + "------------".PadRight(20), + "----".PadRight(5), + "--------"); + foreach (XElement e in xRoot.DescendantsAndSelf()) + Console.WriteLine("{0}{1}{2}", + ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), + ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), + ((IXmlLineInfo)e).LinePosition); +} +``` + +```vb +Dim markup As String = _ + "" & Environment.NewLine & _ + " " & Environment.NewLine & _ + " " & Environment.NewLine & _ + " " & Environment.NewLine & _ + "" + +' Create a reader and move to the content. +Using nodeReader As XmlReader = XmlReader.Create(New StringReader(markup)) + + ' the reader must be in the Interactive state in order to + ' Create a LINQ to XML tree from it. + nodeReader.MoveToContent() + + Dim xRoot As XElement = XElement.Load(nodeReader, LoadOptions.SetLineInfo) + Console.WriteLine("{0}{1}{2}", _ + "Element Name".PadRight(20), _ + "Line".PadRight(5), _ + "Position") + Console.WriteLine("{0}{1}{2}", _ + "------------".PadRight(20), _ + "----".PadRight(5), _ + "--------") + For Each e As XElement In xRoot.DescendantsAndSelf() + Console.WriteLine("{0}{1}{2}", _ + ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString).PadRight(20), _ + (DirectCast(e, IXmlLineInfo)).LineNumber.ToString().PadRight(5), _ + (DirectCast(e, IXmlLineInfo)).LinePosition) + Next +End Using +``` + + This example produces the following output: + +``` +Element Name Line Position +------------ ---- -------- +Root 1 2 + Child 2 6 + GrandChild 3 10 +``` + ]]> LINQ to XML overview @@ -3875,6 +3875,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -3926,6 +3927,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ]]> + The cancellation token was canceled. This exception is stored into the returned task. @@ -3967,6 +3969,7 @@ This method stores in the task it returns all non-usage exceptions that the meth Asynchronously creates a new and initializes its underlying XML tree using the specified XML reader, optionally preserving white space. A new containing the contents of the specified reader. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -4012,58 +4015,58 @@ This method stores in the task it returns all non-usage exceptions that the meth Gets or sets the name of this element. An that contains the name of this element. - and the events. - - - -## Examples - The following example uses this property to determine the name of an element. - -```csharp -XElement el1 = new XElement("Root", "content"); -Console.WriteLine(el1.Name); - -XNamespace ns = "http://www.adventure-works.com"; -XElement el2 = new XElement(ns + "Root", "content"); -Console.WriteLine(el2.Name); -Console.WriteLine(el2.Name.Namespace); -Console.WriteLine(el2.Name.LocalName); -el2.Name = ns + "NewName"; -Console.WriteLine(el2.Name); -``` - -```vb -Imports - -Module Module1 - Sub Main() - Dim el1 As XElement = content - Console.WriteLine(el1.Name) - - Dim el2 As XElement = content - Console.WriteLine(el2.Name) - Console.WriteLine(el2.Name.Namespace) - Console.WriteLine(el2.Name.LocalName) - Dim aw as XNamespace = GetXmlNamespace(aw) - el2.Name = aw + "NewName" - Console.WriteLine(el2.Name) - End Sub -End Module -``` - - This example produces the following output: - -``` -Root -{http://www.adventure-works.com}Root -http://www.adventure-works.com -Root -{http://www.adventure-works.com}NewName -``` - + and the events. + + + +## Examples + The following example uses this property to determine the name of an element. + +```csharp +XElement el1 = new XElement("Root", "content"); +Console.WriteLine(el1.Name); + +XNamespace ns = "http://www.adventure-works.com"; +XElement el2 = new XElement(ns + "Root", "content"); +Console.WriteLine(el2.Name); +Console.WriteLine(el2.Name.Namespace); +Console.WriteLine(el2.Name.LocalName); +el2.Name = ns + "NewName"; +Console.WriteLine(el2.Name); +``` + +```vb +Imports + +Module Module1 + Sub Main() + Dim el1 As XElement = content + Console.WriteLine(el1.Name) + + Dim el2 As XElement = content + Console.WriteLine(el2.Name) + Console.WriteLine(el2.Name.Namespace) + Console.WriteLine(el2.Name.LocalName) + Dim aw as XNamespace = GetXmlNamespace(aw) + el2.Name = aw + "NewName" + Console.WriteLine(el2.Name) + End Sub +End Module +``` + + This example produces the following output: + +``` +Root +{http://www.adventure-works.com}Root +http://www.adventure-works.com +Root +{http://www.adventure-works.com}NewName +``` + ]]> LINQ to XML overview @@ -4106,34 +4109,34 @@ Root Gets the node type for this node. The node type. For objects, this value is . - contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. - - - -## Examples - The following example uses this property to print the node type of an element. - -```csharp -XElement el1 = new XElement("Root", "content"); -Console.WriteLine(el1.NodeType); -Console.WriteLine(); -``` - -```vb -Dim el1 As XElement = content -Console.WriteLine(el1.NodeType.ToString()) -Console.WriteLine() -``` - - This example produces the following output: - -``` -Element -``` - + contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. + + + +## Examples + The following example uses this property to print the node type of an element. + +```csharp +XElement el1 = new XElement("Root", "content"); +Console.WriteLine(el1.NodeType); +Console.WriteLine(); +``` + +```vb +Dim el1 As XElement = content +Console.WriteLine(el1.NodeType.ToString()) +Console.WriteLine() +``` + + This example produces the following output: + +``` +Element +``` + ]]> LINQ to XML overview @@ -4186,44 +4189,44 @@ Element Cast the value of this to a . A that contains the content of this . - from an attribute or element, allowed values are "0", "1", and any string that produces "true" or "false" after trimming and conversion to lower case. - -## Examples - The following example creates some elements with boolean values. It then casts them to . - -```csharp -XElement root = new XElement("Root", - new XElement("BoolValue1", true), - new XElement("BoolValue2", false) -); -bool bool1 = (bool)root.Element("BoolValue1"); -bool bool2 = (bool)root.Element("BoolValue2"); -Console.WriteLine("(bool)BoolValue1={0}", bool1); -Console.WriteLine("(bool)BoolValue2={0}", bool2); -``` - -```vb -Dim root As XElement = _ - - true - false - -Dim bool1 As Boolean = CBool(root.Element("BoolValue1")) -Dim bool2 As Boolean = CBool(root.Element("BoolValue2")) -Console.WriteLine("(bool)BoolValue1={0}", bool1) -Console.WriteLine("(bool)BoolValue2={0}", bool2) -``` - - This example produces the following output: - -``` -(bool)BoolValue1=True -(bool)BoolValue2=False -``` - + +## Examples + The following example creates some elements with boolean values. It then casts them to . + +```csharp +XElement root = new XElement("Root", + new XElement("BoolValue1", true), + new XElement("BoolValue2", false) +); +bool bool1 = (bool)root.Element("BoolValue1"); +bool bool2 = (bool)root.Element("BoolValue2"); +Console.WriteLine("(bool)BoolValue1={0}", bool1); +Console.WriteLine("(bool)BoolValue2={0}", bool2); +``` + +```vb +Dim root As XElement = _ + + true + false + +Dim bool1 As Boolean = CBool(root.Element("BoolValue1")) +Dim bool2 As Boolean = CBool(root.Element("BoolValue2")) +Console.WriteLine("(bool)BoolValue1={0}", bool1) +Console.WriteLine("(bool)BoolValue2={0}", bool2) +``` + + This example produces the following output: + +``` +(bool)BoolValue1=True +(bool)BoolValue2=False +``` + ]]> The element does not contain a valid value. @@ -4278,64 +4281,64 @@ Console.WriteLine("(bool)BoolValue2={0}", bool2) Cast the value of this to a . A that contains the content of this . - from an attribute or element. Even if the attribute or element value is not formatted exactly per the W3C specification, the value is appropriately converted to a . - + from an attribute or element. Even if the attribute or element value is not formatted exactly per the W3C specification, the value is appropriately converted to a . + This conversion operator uses to convert from a . -## Examples - The following example creates an element with date and time content. It then casts it to to retrieve the value. - -```csharp -// Behavior is strict when formatting an XML element or attribute from a DateTime, -// but behavior is lax when casting to a DateTime from an element or attribute. -XElement root = new XElement("Root", new DateTime(2006, 10, 6, 12, 30, 0)); -Console.WriteLine(root); - -// Cast from a strictly formatted XML element. -DateTime dt = (DateTime)root; -Console.WriteLine("dt={0}", dt); -Console.WriteLine("-----"); - -// If root is formatted in some different way: -XElement dtElement = new XElement("OrderDate", "October 6, 2006"); -Console.WriteLine(dtElement); -DateTime orderDate = (DateTime)dtElement; -Console.WriteLine("orderDate={0:d}", orderDate); -``` - -```vb -' Behavior is strict when formatting an XML element or attribute from a DateTime, -' but behavior is lax when casting to a DateTime from an element or attribute. -Dim root As XElement = <%= New DateTime(2006, 10, 6, 12, 30, 0) %> -Console.WriteLine(root) - -' Cast from a strictly formatted XML element. -Dim dt As DateTime = CType(root, DateTime) -Console.WriteLine("dt={0}", dt) -Console.WriteLine("-----") - -' If root is formatted in some different way: -Dim dtElement As XElement = October 6, 2006 -Console.WriteLine(dtElement) -Dim orderDate As DateTime = CType(dtElement, DateTime) -Console.WriteLine("orderDate={0:d}", orderDate) -``` - - This example produces the following output: - -``` -2006-10-06T12:30:00 -dt=10/6/2006 12:30:00 PM ------ -October 6, 2006 -orderDate=10/6/2006 -``` - +## Examples + The following example creates an element with date and time content. It then casts it to to retrieve the value. + +```csharp +// Behavior is strict when formatting an XML element or attribute from a DateTime, +// but behavior is lax when casting to a DateTime from an element or attribute. +XElement root = new XElement("Root", new DateTime(2006, 10, 6, 12, 30, 0)); +Console.WriteLine(root); + +// Cast from a strictly formatted XML element. +DateTime dt = (DateTime)root; +Console.WriteLine("dt={0}", dt); +Console.WriteLine("-----"); + +// If root is formatted in some different way: +XElement dtElement = new XElement("OrderDate", "October 6, 2006"); +Console.WriteLine(dtElement); +DateTime orderDate = (DateTime)dtElement; +Console.WriteLine("orderDate={0:d}", orderDate); +``` + +```vb +' Behavior is strict when formatting an XML element or attribute from a DateTime, +' but behavior is lax when casting to a DateTime from an element or attribute. +Dim root As XElement = <%= New DateTime(2006, 10, 6, 12, 30, 0) %> +Console.WriteLine(root) + +' Cast from a strictly formatted XML element. +Dim dt As DateTime = CType(root, DateTime) +Console.WriteLine("dt={0}", dt) +Console.WriteLine("-----") + +' If root is formatted in some different way: +Dim dtElement As XElement = October 6, 2006 +Console.WriteLine(dtElement) +Dim orderDate As DateTime = CType(dtElement, DateTime) +Console.WriteLine("orderDate={0:d}", orderDate) +``` + + This example produces the following output: + +``` +2006-10-06T12:30:00 +dt=10/6/2006 12:30:00 PM +----- +October 6, 2006 +orderDate=10/6/2006 +``` + ]]> The element does not contain a valid value. @@ -4392,44 +4395,44 @@ orderDate=10/6/2006 Cast the value of this to a . A that contains the content of this . - class to do the conversion. - -## Examples - The following example creates an element with date and time content. It then casts to to retrieve the value. - -```csharp -XElement root = new XElement("Root", - new XElement("Child", new DateTimeOffset(new DateTime(2006, 10, 6, 12, 30, 0))) -); -Console.WriteLine(root); - -DateTimeOffset dt = (DateTimeOffset)root.Element("Child"); -Console.WriteLine("dt={0}", dt); -``` - -```vb -Dim root As XElement = _ - - <%= New DateTimeOffset(New DateTime(2006, 10, 6, 12, 30, 0)) %> - -Console.WriteLine(root) - -Dim dt As DateTimeOffset = CType(root.(0), DateTimeOffset) -Console.WriteLine("dt={0}", dt) -``` - - This example produces the following output: - -``` - - 2006-10-06T12:30:00-07:00 - -dt=10/6/2006 12:30:00 PM -07:00 -``` - + class to do the conversion. + +## Examples + The following example creates an element with date and time content. It then casts to to retrieve the value. + +```csharp +XElement root = new XElement("Root", + new XElement("Child", new DateTimeOffset(new DateTime(2006, 10, 6, 12, 30, 0))) +); +Console.WriteLine(root); + +DateTimeOffset dt = (DateTimeOffset)root.Element("Child"); +Console.WriteLine("dt={0}", dt); +``` + +```vb +Dim root As XElement = _ + + <%= New DateTimeOffset(New DateTime(2006, 10, 6, 12, 30, 0)) %> + +Console.WriteLine(root) + +Dim dt As DateTimeOffset = CType(root.(0), DateTimeOffset) +Console.WriteLine("dt={0}", dt) +``` + + This example produces the following output: + +``` + + 2006-10-06T12:30:00-07:00 + +dt=10/6/2006 12:30:00 PM -07:00 +``` + ]]> The element does not contain a valid value. @@ -4487,29 +4490,29 @@ dt=10/6/2006 12:30:00 PM -07:00 A that contains the content of this . . - -```csharp -XElement root = new XElement("Root", "79228162514264337593543950335"); -decimal value = (decimal)root; -Console.WriteLine("value={0}", value); -``` - -```vb -Dim root As XElement = 79228162514264337593543950335 -Dim value As Decimal = CDec(root) -Console.WriteLine("value={0}", value) - -``` - - This example produces the following output: - -``` -value=79228162514264337593543950335 -``` - + +## Examples + The following example creates an element with a decimal value. It then retrieves the value of the attribute by casting to . + +```csharp +XElement root = new XElement("Root", "79228162514264337593543950335"); +decimal value = (decimal)root; +Console.WriteLine("value={0}", value); +``` + +```vb +Dim root As XElement = 79228162514264337593543950335 +Dim value As Decimal = CDec(root) +Console.WriteLine("value={0}", value) + +``` + + This example produces the following output: + +``` +value=79228162514264337593543950335 +``` + ]]> The element does not contain a valid value. @@ -4566,28 +4569,28 @@ value=79228162514264337593543950335 Cast the value of this to a . A that contains the content of this . - . - -```csharp -XElement root = new XElement("Root", 1.79769313486231e308); -double value = (double)root; -Console.WriteLine("value={0}", value); -``` - -```vb -Dim root As XElement = 1.79769313486231E+308 -Dim value As Double = CDbl(root) -Console.WriteLine("value={0}", value) -``` - - This example produces the following output: - -``` -value=1.79769313486231E+308 -``` - + . + +```csharp +XElement root = new XElement("Root", 1.79769313486231e308); +double value = (double)root; +Console.WriteLine("value={0}", value); +``` + +```vb +Dim root As XElement = 1.79769313486231E+308 +Dim value As Double = CDbl(root) +Console.WriteLine("value={0}", value) +``` + + This example produces the following output: + +``` +value=1.79769313486231E+308 +``` + ]]> The element does not contain a valid value. @@ -4645,28 +4648,28 @@ value=1.79769313486231E+308 A that contains the content of this . . - -```csharp -XElement root = new XElement("Root", new Guid("3c1cc55b-baff-4b7a-9d17-077af3aa5730")); -Guid value = (Guid)root; -Console.WriteLine("value={0}", value); -``` - -```vb -Dim root As XElement = <%= New Guid("3c1cc55b-baff-4b7a-9d17-077af3aa5730") %> -Dim value As Guid = CType(root, Guid) -Console.WriteLine("value={0}", value) -``` - - This example produces the following output: - -``` -value=3c1cc55b-baff-4b7a-9d17-077af3aa5730 -``` - + +## Examples + The following example creates an element with a guid as content. It then retrieves the value by casting to . + +```csharp +XElement root = new XElement("Root", new Guid("3c1cc55b-baff-4b7a-9d17-077af3aa5730")); +Guid value = (Guid)root; +Console.WriteLine("value={0}", value); +``` + +```vb +Dim root As XElement = <%= New Guid("3c1cc55b-baff-4b7a-9d17-077af3aa5730") %> +Dim value As Guid = CType(root, Guid) +Console.WriteLine("value={0}", value) +``` + + This example produces the following output: + +``` +value=3c1cc55b-baff-4b7a-9d17-077af3aa5730 +``` + ]]> The element does not contain a valid value. @@ -4724,28 +4727,28 @@ value=3c1cc55b-baff-4b7a-9d17-077af3aa5730 A that contains the content of this . . - -```csharp -XElement root = new XElement("Root", 2147483647); -int value = (int)root; -Console.WriteLine("value={0}", value); -``` - -```vb -Dim root As XElement = 2147483647 -Dim value As Integer = CInt(root) -Console.WriteLine("value={0}", value) -``` - - This example produces the following output: - -``` -value=2147483647 -``` - + +## Examples + The following example creates an element with an integer as content. It then retrieves the value by casting to . + +```csharp +XElement root = new XElement("Root", 2147483647); +int value = (int)root; +Console.WriteLine("value={0}", value); +``` + +```vb +Dim root As XElement = 2147483647 +Dim value As Integer = CInt(root) +Console.WriteLine("value={0}", value) +``` + + This example produces the following output: + +``` +value=2147483647 +``` + ]]> The element does not contain a valid value. @@ -4801,28 +4804,28 @@ value=2147483647 A that contains the content of this . . - -```csharp -XElement root = new XElement("Root", 9223372036854775807); -long value = (long)root; -Console.WriteLine("value={0}", value); -``` - -```vb -Dim root As XElement = 9223372036854775807 -Dim value As Long = CLng(root) -Console.WriteLine("value={0}", value) -``` - - This example produces the following output: - -``` -value=9223372036854775807 -``` - + +## Examples + The following example creates an element with a long integer as content. It then retrieves the value of the element by casting to . + +```csharp +XElement root = new XElement("Root", 9223372036854775807); +long value = (long)root; +Console.WriteLine("value={0}", value); +``` + +```vb +Dim root As XElement = 9223372036854775807 +Dim value As Long = CLng(root) +Console.WriteLine("value={0}", value) +``` + + This example produces the following output: + +``` +value=9223372036854775807 +``` + ]]> The element does not contain a valid value. @@ -4880,44 +4883,44 @@ value=9223372036854775807 Cast the value of this to a of . A of that contains the content of this . - of from an attribute or element, allowed values are "0", "1", and any string that produces "true" or "false" after trimming and conversion to lower case. - -## Examples - The following example creates an element with boolean content. It then retrieves the value by casting to of . - -```csharp -XElement root = new XElement("Root", - new XElement("BoolValue1", true), - new XElement("BoolValue2", false)); -bool? bool1 = (bool?)root.Element("BoolValue1"); -bool? bool2 = (bool?)root.Element("BoolValue2"); -Console.WriteLine("Nullable Boolean: value1={0}", bool1); -Console.WriteLine("Nullable Boolean: value2={0}", bool2); -``` - -```vb -Dim root As XElement = _ - - true - false - - -Dim value1 As Nullable(Of Boolean) = CType(root.Element("BoolValue1"), Nullable(Of Boolean)) -Dim value2 As Nullable(Of Boolean) = CType(root.Element("BoolValue2"), Nullable(Of Boolean)) -Console.WriteLine("Nullable Boolean: value1={0}", IIf(value1.HasValue, value1.ToString(), "null")) -Console.WriteLine("Nullable Boolean: value2={0}", IIf(value2.HasValue, value2.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable Boolean: value1=True -Nullable Boolean: value2=False -``` - + +## Examples + The following example creates an element with boolean content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("BoolValue1", true), + new XElement("BoolValue2", false)); +bool? bool1 = (bool?)root.Element("BoolValue1"); +bool? bool2 = (bool?)root.Element("BoolValue2"); +Console.WriteLine("Nullable Boolean: value1={0}", bool1); +Console.WriteLine("Nullable Boolean: value2={0}", bool2); +``` + +```vb +Dim root As XElement = _ + + true + false + + +Dim value1 As Nullable(Of Boolean) = CType(root.Element("BoolValue1"), Nullable(Of Boolean)) +Dim value2 As Nullable(Of Boolean) = CType(root.Element("BoolValue2"), Nullable(Of Boolean)) +Console.WriteLine("Nullable Boolean: value1={0}", IIf(value1.HasValue, value1.ToString(), "null")) +Console.WriteLine("Nullable Boolean: value2={0}", IIf(value2.HasValue, value2.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable Boolean: value1=True +Nullable Boolean: value2=False +``` + ]]> The element is not and does not contain a valid value. @@ -4972,41 +4975,41 @@ Nullable Boolean: value2=False Cast the value of this to a of . A of that contains the content of this . - of from an attribute or element. Even if the attribute or element value is not formatted exactly per the W3C specification, the value is appropriately converted to a of . - + of from an attribute or element. Even if the attribute or element value is not formatted exactly per the W3C specification, the value is appropriately converted to a of . + This conversion operator uses to convert from a . - -## Examples - The following example creates an element with a date and time as content. It then retrieves the value by casting to of . - + +## Examples + The following example creates an element with a date and time as content. It then retrieves the value by casting to of . + ```csharp -XElement root = new XElement("Root", - new XElement("Value", new DateTime(2006, 10, 6, 12, 30, 0)) -); -DateTime? value = (DateTime?)root.Element("Value"); -Console.WriteLine("Nullable DateTime: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - <%= New DateTime(2006, 10, 6, 12, 30, 0) %> - -Dim value As Nullable(Of DateTime) = CType(root.Element("Value"), Nullable(Of DateTime)) -Console.WriteLine("Nullable DateTime: value={0}", IIf(value.HasValue, value.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable DateTime: value=10/6/2006 12:30:00 PM -``` - +XElement root = new XElement("Root", + new XElement("Value", new DateTime(2006, 10, 6, 12, 30, 0)) +); +DateTime? value = (DateTime?)root.Element("Value"); +Console.WriteLine("Nullable DateTime: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + <%= New DateTime(2006, 10, 6, 12, 30, 0) %> + +Dim value As Nullable(Of DateTime) = CType(root.Element("Value"), Nullable(Of DateTime)) +Console.WriteLine("Nullable DateTime: value={0}", IIf(value.HasValue, value.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable DateTime: value=10/6/2006 12:30:00 PM +``` + ]]> The element is not and does not contain a valid value. @@ -5061,44 +5064,44 @@ Nullable DateTime: value=10/6/2006 12:30:00 PM Cast the value of this to a of . A of that contains the content of this . - class to do the conversion. - -## Examples - The following example creates an element with date and time content. It then casts to of to retrieve the value. - -```csharp -XElement root = new XElement("Root", - new XElement("Child", new DateTimeOffset(new DateTime(2006, 10, 6, 12, 30, 0))) -); -Console.WriteLine(root); - -DateTimeOffset? dt = (DateTimeOffset?)root.Element("Child"); -Console.WriteLine("dt={0}", dt); -``` - -```vb -Dim root As XElement = _ - - <%= New DateTimeOffset(New DateTime(2006, 10, 6, 12, 30, 0)) %> - -Console.WriteLine(root) - -Dim dt As Nullable(Of DateTimeOffset) = CType(root.(0), Nullable(Of DateTimeOffset)) -Console.WriteLine("dt={0}", dt) -``` - - This example produces the following output: - -``` - - 2006-10-06T12:30:00-07:00 - -dt=10/6/2006 12:30:00 PM -07:00 -``` - + +## Examples + The following example creates an element with date and time content. It then casts to of to retrieve the value. + +```csharp +XElement root = new XElement("Root", + new XElement("Child", new DateTimeOffset(new DateTime(2006, 10, 6, 12, 30, 0))) +); +Console.WriteLine(root); + +DateTimeOffset? dt = (DateTimeOffset?)root.Element("Child"); +Console.WriteLine("dt={0}", dt); +``` + +```vb +Dim root As XElement = _ + + <%= New DateTimeOffset(New DateTime(2006, 10, 6, 12, 30, 0)) %> + +Console.WriteLine(root) + +Dim dt As Nullable(Of DateTimeOffset) = CType(root.(0), Nullable(Of DateTimeOffset)) +Console.WriteLine("dt={0}", dt) +``` + + This example produces the following output: + +``` + + 2006-10-06T12:30:00-07:00 + +dt=10/6/2006 12:30:00 PM -07:00 +``` + ]]> The element is not and does not contain a valid value. @@ -5154,33 +5157,33 @@ dt=10/6/2006 12:30:00 PM -07:00 A of that contains the content of this . of . - -```csharp -XElement root = new XElement("Root", - new XElement("Value", "79228162514264337593543950335") -); -decimal? value = (decimal?)root.Element("Value"); -Console.WriteLine("Nullable decimal: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - 79228162514264337593543950335 - -Dim value As Nullable(Of Decimal) = CType(root.Element("Value"), Nullable(Of Decimal)) -Console.WriteLine("Nullable decimal: value={0}", IIf(value.HasValue, value.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable decimal: value=79228162514264337593543950335 -``` - + +## Examples + The following example creates an element with decimal content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("Value", "79228162514264337593543950335") +); +decimal? value = (decimal?)root.Element("Value"); +Console.WriteLine("Nullable decimal: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + 79228162514264337593543950335 + +Dim value As Nullable(Of Decimal) = CType(root.Element("Value"), Nullable(Of Decimal)) +Console.WriteLine("Nullable decimal: value={0}", IIf(value.HasValue, value.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable decimal: value=79228162514264337593543950335 +``` + ]]> The element is not and does not contain a valid value. @@ -5237,33 +5240,33 @@ Nullable decimal: value=79228162514264337593543950335 of . - -```csharp -XElement root = new XElement("Root", - new XElement("Value", 1.79769313486231e308) -); -double? value = (double?)root.Element("Value"); -Console.WriteLine("Nullable double: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - 1.79769313486231e308 - - -Dim value As Nullable(Of Double) = CType(root.Element("Value"), Nullable(Of Double)) -Console.WriteLine("Nullable double: value={0}", IIf(value.HasValue, value.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable double: value=1.79769313486231E+308 -``` - +## Examples + The following example creates an element with double precision floating point content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("Value", 1.79769313486231e308) +); +double? value = (double?)root.Element("Value"); +Console.WriteLine("Nullable double: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + 1.79769313486231e308 + + +Dim value As Nullable(Of Double) = CType(root.Element("Value"), Nullable(Of Double)) +Console.WriteLine("Nullable double: value={0}", IIf(value.HasValue, value.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable double: value=1.79769313486231E+308 +``` + ]]> The element is not and does not contain a valid value. @@ -5320,32 +5323,32 @@ Nullable double: value=1.79769313486231E+308 of . - -```csharp -XElement root = new XElement("Root", - new XElement("Value", new Guid("3c1cc55b-baff-4b7a-9d17-077af3aa5730")) -); -Guid? value = (Guid?)root.Element("Value"); -Console.WriteLine("Nullable Guid: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - <%= New Guid("3c1cc55b-baff-4b7a-9d17-077af3aa5730") %> - -Dim value As Nullable(Of Guid) = CType(root.Element("Value"), Nullable(Of Guid)) -Console.WriteLine("Nullable Guid: value={0}", IIf(value.HasValue, value.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable Guid: value=3c1cc55b-baff-4b7a-9d17-077af3aa5730 -``` - +## Examples + The following example creates an element with guid content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("Value", new Guid("3c1cc55b-baff-4b7a-9d17-077af3aa5730")) +); +Guid? value = (Guid?)root.Element("Value"); +Console.WriteLine("Nullable Guid: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + <%= New Guid("3c1cc55b-baff-4b7a-9d17-077af3aa5730") %> + +Dim value As Nullable(Of Guid) = CType(root.Element("Value"), Nullable(Of Guid)) +Console.WriteLine("Nullable Guid: value={0}", IIf(value.HasValue, value.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable Guid: value=3c1cc55b-baff-4b7a-9d17-077af3aa5730 +``` + ]]> The element is not and does not contain a valid value. @@ -5402,33 +5405,33 @@ Nullable Guid: value=3c1cc55b-baff-4b7a-9d17-077af3aa5730 of . - -```csharp -XElement root = new XElement("Root", - new XElement("Value", 2147483647) -); -int? value = (int?)root.Element("Value"); -Console.WriteLine("Nullable integer: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - 2147483647 - -Dim value As Nullable(Of Integer) = CType(root.Element("Value"), Nullable(Of Integer)) -Console.WriteLine("Nullable integer: value={0}", IIf(value.HasValue, value.ToString(), "null")) - -``` - - This example produces the following output: - -``` -Nullable integer: value=2147483647 -``` - +## Examples + The following example creates an element with unsigned integer content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("Value", 2147483647) +); +int? value = (int?)root.Element("Value"); +Console.WriteLine("Nullable integer: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + 2147483647 + +Dim value As Nullable(Of Integer) = CType(root.Element("Value"), Nullable(Of Integer)) +Console.WriteLine("Nullable integer: value={0}", IIf(value.HasValue, value.ToString(), "null")) + +``` + + This example produces the following output: + +``` +Nullable integer: value=2147483647 +``` + ]]> The element is not and does not contain a valid value. @@ -5485,32 +5488,32 @@ Nullable integer: value=2147483647 of . - -```csharp -XElement root = new XElement("Root", - new XElement("Value", 9223372036854775807) -); -ulong? value = (ulong?)root.Element("Value"); -Console.WriteLine("Nullable ulong: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - 9223372036854775807 - -Dim value As Nullable(Of ULong) = CType(root.Element("Value"), Nullable(Of ULong)) -Console.WriteLine("Nullable ulong: value={0}", IIf(value.HasValue, value.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable ulong: value=9223372036854775807 -``` - +## Examples + The following example creates an element with long integer content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("Value", 9223372036854775807) +); +ulong? value = (ulong?)root.Element("Value"); +Console.WriteLine("Nullable ulong: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + 9223372036854775807 + +Dim value As Nullable(Of ULong) = CType(root.Element("Value"), Nullable(Of ULong)) +Console.WriteLine("Nullable ulong: value={0}", IIf(value.HasValue, value.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable ulong: value=9223372036854775807 +``` + ]]> The element is not and does not contain a valid value. @@ -5567,32 +5570,32 @@ Nullable ulong: value=9223372036854775807 of . - -```csharp -XElement root = new XElement("Root", - new XElement("Value", 3.402823e38) -); -float? value = (float?)root.Element("Value"); -Console.WriteLine("Nullable Single: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - 3.402823e38 - -Dim value As Nullable(Of Single) = CType(root.Element("Value"), Nullable(Of Single)) -Console.WriteLine("Nullable Single: value={0}", IIf(value.HasValue, value.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable Single: value=3.402823E+38 -``` - +## Examples + The following example creates an element with single precision floating point content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("Value", 3.402823e38) +); +float? value = (float?)root.Element("Value"); +Console.WriteLine("Nullable Single: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + 3.402823e38 + +Dim value As Nullable(Of Single) = CType(root.Element("Value"), Nullable(Of Single)) +Console.WriteLine("Nullable Single: value={0}", IIf(value.HasValue, value.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable Single: value=3.402823E+38 +``` + ]]> The element is not and does not contain a valid value. @@ -5647,39 +5650,39 @@ Nullable Single: value=3.402823E+38 Cast the value of this to a of . A of that contains the content of this . - of from an attribute or element. Even if the attribute or element value is not formatted exactly per the W3C specification, the value is appropriately converted to a of . - -## Examples - The following example creates an element with time span content. It then retrieves the value by casting to of . - -```csharp -XElement root = new XElement("Root", - new XElement("Value", new TimeSpan(1, 5, 30)) -); -TimeSpan? value = (TimeSpan?)root.Element("Value"); -Console.WriteLine("Nullable TimeSpan: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - <%= New TimeSpan(1, 5, 30) %> - -Dim value As Nullable(Of TimeSpan) = CType(root.Element("Value"), Nullable(Of TimeSpan)) -Console.WriteLine("Nullable TimeSpan: value={0}", IIf(value.HasValue, value.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable TimeSpan: value=01:05:30 -``` - + +## Examples + The following example creates an element with time span content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("Value", new TimeSpan(1, 5, 30)) +); +TimeSpan? value = (TimeSpan?)root.Element("Value"); +Console.WriteLine("Nullable TimeSpan: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + <%= New TimeSpan(1, 5, 30) %> + +Dim value As Nullable(Of TimeSpan) = CType(root.Element("Value"), Nullable(Of TimeSpan)) +Console.WriteLine("Nullable TimeSpan: value={0}", IIf(value.HasValue, value.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable TimeSpan: value=01:05:30 +``` + ]]> The element is not and does not contain a valid value. @@ -5736,32 +5739,32 @@ Nullable TimeSpan: value=01:05:30 of . - -```csharp -XElement root = new XElement("Root", - new XElement("Value", 4294967295) -); -uint? value = (uint?)root.Element("Value"); -Console.WriteLine("Nullable uint: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - 4294967295 - -Dim value As Nullable(Of UInteger) = CType(root.Element("Value"), Nullable(Of UInteger)) -Console.WriteLine("Nullable uint: value={0}", IIf(value.HasValue, value.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable uint: value=4294967295 -``` - +## Examples + The following example creates an element with unsigned integer content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("Value", 4294967295) +); +uint? value = (uint?)root.Element("Value"); +Console.WriteLine("Nullable uint: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + 4294967295 + +Dim value As Nullable(Of UInteger) = CType(root.Element("Value"), Nullable(Of UInteger)) +Console.WriteLine("Nullable uint: value={0}", IIf(value.HasValue, value.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable uint: value=4294967295 +``` + ]]> The element is not and does not contain a valid value. @@ -5818,33 +5821,33 @@ Nullable uint: value=4294967295 of . - -```csharp -XElement root = new XElement("Root", - new XElement("Value", 9223372036854775807) -); -ulong? value = (ulong?)root.Element("Value"); -Console.WriteLine("Nullable ulong: value={0}", value == null ? "null" : value.ToString()); -``` - -```vb -Dim root As XElement = _ - - 9223372036854775807 - - -Dim value As Nullable(Of ULong) = CType(root.Element("Value"), Nullable(Of ULong)) -Console.WriteLine("Nullable ulong: value={0}", IIf(value.HasValue, value.ToString(), "null")) -``` - - This example produces the following output: - -``` -Nullable ulong: value=9223372036854775807 -``` - +## Examples + The following example creates an element with unsigned long integer content. It then retrieves the value by casting to of . + +```csharp +XElement root = new XElement("Root", + new XElement("Value", 9223372036854775807) +); +ulong? value = (ulong?)root.Element("Value"); +Console.WriteLine("Nullable ulong: value={0}", value == null ? "null" : value.ToString()); +``` + +```vb +Dim root As XElement = _ + + 9223372036854775807 + + +Dim value As Nullable(Of ULong) = CType(root.Element("Value"), Nullable(Of ULong)) +Console.WriteLine("Nullable ulong: value={0}", IIf(value.HasValue, value.ToString(), "null")) +``` + + This example produces the following output: + +``` +Nullable ulong: value=9223372036854775807 +``` + ]]> The element is not and does not contain a valid value. @@ -5899,28 +5902,28 @@ Nullable ulong: value=9223372036854775807 A that contains the content of this . . - -```csharp -XElement root = new XElement("Root", 3.402823e38); -float value = (float)root; -Console.WriteLine("value={0}", value); -``` - -```vb -Dim root As XElement = 3.402823E+38 -Dim value As Single = CSng(root) -Console.WriteLine("value={0}", value) -``` - - This example produces the following output: - -``` -value=3.402823E+38 -``` - + +## Examples + The following example creates an element with single precision floating point content. It then retrieves the value by casting to . + +```csharp +XElement root = new XElement("Root", 3.402823e38); +float value = (float)root; +Console.WriteLine("value={0}", value); +``` + +```vb +Dim root As XElement = 3.402823E+38 +Dim value As Single = CSng(root) +Console.WriteLine("value={0}", value) +``` + + This example produces the following output: + +``` +value=3.402823E+38 +``` + ]]> The element does not contain a valid value. @@ -5978,30 +5981,30 @@ value=3.402823E+38 Cast the value of this to a . A that contains the content of this . - has children, the concatenated string value of all of the element's text and descendant's text is returned. - -## Examples - The following example creates an element with string content. It then retrieves the value by casting to . - -```csharp -XElement root = XElement.Parse("abc def ghi"); -Console.WriteLine("(string)root={0}", (string)root); -``` - -```vb -Dim root As XElement = abc def ghi -Console.WriteLine("(string)root={0}", root.Value) -``` - - This example produces the following output: - -``` -(string)root=abc def ghi -``` - + has children, the concatenated string value of all of the element's text and descendant's text is returned. + +## Examples + The following example creates an element with string content. It then retrieves the value by casting to . + +```csharp +XElement root = XElement.Parse("abc def ghi"); +Console.WriteLine("(string)root={0}", (string)root); +``` + +```vb +Dim root As XElement = abc def ghi +Console.WriteLine("(string)root={0}", root.Value) +``` + + This example produces the following output: + +``` +(string)root=abc def ghi +``` + ]]> LINQ to XML overview @@ -6054,34 +6057,34 @@ Console.WriteLine("(string)root={0}", root.Value) Cast the value of this to a . A that contains the content of this . - from an attribute or element. Even if the attribute or element value is not formatted exactly per the W3C specification, the value is appropriately converted to a . - -## Examples - The following example creates an element with time span content. It then retrieves the value by casting to . - -```csharp -XElement root = new XElement("Root", new TimeSpan(1, 5, 30)); -TimeSpan value = (TimeSpan)root; -Console.WriteLine("value={0}", value); -``` - -```vb -Dim root As XElement = <%= New TimeSpan(1, 5, 30) %> -Dim value As TimeSpan = CType(root, TimeSpan) -Console.WriteLine("value={0}", value) -``` - - This example produces the following output: - -``` -value=01:05:30 -``` - + +## Examples + The following example creates an element with time span content. It then retrieves the value by casting to . + +```csharp +XElement root = new XElement("Root", new TimeSpan(1, 5, 30)); +TimeSpan value = (TimeSpan)root; +Console.WriteLine("value={0}", value); +``` + +```vb +Dim root As XElement = <%= New TimeSpan(1, 5, 30) %> +Dim value As TimeSpan = CType(root, TimeSpan) +Console.WriteLine("value={0}", value) +``` + + This example produces the following output: + +``` +value=01:05:30 +``` + ]]> The element does not contain a valid value. @@ -6138,27 +6141,27 @@ value=01:05:30 . - -```csharp -XElement root = new XElement("Root", 4294967295); -uint value = (uint)root; -Console.WriteLine("value={0}", value); -``` - -```vb -Dim root As XElement = 4294967295 -Dim value As UInteger = CUInt(root) -Console.WriteLine("value={0}", value) -``` - - This example produces the following output: - -``` -value=4294967295 -``` - +## Examples + The following example creates an element with unsigned integer content. It then retrieves the value by casting to . + +```csharp +XElement root = new XElement("Root", 4294967295); +uint value = (uint)root; +Console.WriteLine("value={0}", value); +``` + +```vb +Dim root As XElement = 4294967295 +Dim value As UInteger = CUInt(root) +Console.WriteLine("value={0}", value) +``` + + This example produces the following output: + +``` +value=4294967295 +``` + ]]> The element does not contain a valid value. @@ -6214,28 +6217,28 @@ value=4294967295 A that contains the content of this . . - -```csharp -XElement root = new XElement("Root", 18446744073709551615); -ulong value = (ulong)root; -Console.WriteLine("value={0}", value); -``` - -```vb -Dim root As XElement = 18446744073709551615 -Dim value As ULong = CULng(root) -Console.WriteLine("value={0}", value) -``` - - This example produces the following output: - -``` -value=18446744073709551615 -``` - + +## Examples + The following example creates an element with unsigned long integer content. It then retrieves the value by casting to . + +```csharp +XElement root = new XElement("Root", 18446744073709551615); +ulong value = (ulong)root; +Console.WriteLine("value={0}", value); +``` + +```vb +Dim root As XElement = 18446744073709551615 +Dim value As ULong = CULng(root) +Console.WriteLine("value={0}", value) +``` + + This example produces the following output: + +``` +value=18446744073709551615 +``` + ]]> The element does not contain a valid value. @@ -6304,36 +6307,36 @@ value=18446744073709551615 Load an from a string that contains XML. An populated from the string that contains XML. - method that takes as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example creates a string that contains XML. It then parses the string into an . - -```csharp -XElement xmlTree = XElement.Parse(" "); -Console.WriteLine(xmlTree); -``` - -```vb -Dim xmlTree As XElement = -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - - -``` - + method that takes as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example creates a string that contains XML. It then parses the string into an . + +```csharp +XElement xmlTree = XElement.Parse(" "); +Console.WriteLine(xmlTree); +``` + +```vb +Dim xmlTree As XElement = +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + + +``` + ]]> LINQ to XML overview @@ -6382,144 +6385,144 @@ Console.WriteLine(xmlTree) Load an from a string that contains XML, optionally preserving white space and retaining line information. An populated from the string that contains XML. - flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. - - If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. - - If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - Setting will have no effect when parsing from a . - - The may have a valid line information or not. If you set , the line information will be set in the XML tree from the line information that is reported by the . - - There is a performance penalty if you set the flag. - - The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. - - LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. - - - -## Examples - The following example parses a string into an in two different ways: preserving white space, and not preserving white space. It then uses a query to determine the number of white space nodes in the resulting XML tree. - -```csharp -int whiteSpaceNodes; - -XElement xmlTree1 = XElement.Parse(" ", - LoadOptions.None); -whiteSpaceNodes = xmlTree1 - .DescendantNodesAndSelf() - .OfType() - .Where(tNode => tNode.ToString().Trim().Length == 0) - .Count(); -Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", - whiteSpaceNodes); - -XElement xmlTree2 = XElement.Parse(" ", - LoadOptions.PreserveWhitespace); -whiteSpaceNodes = xmlTree2 - .DescendantNodesAndSelf() - .OfType() - .Where(tNode => tNode.ToString().Trim().Length == 0) - .Count(); -Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", - whiteSpaceNodes); -``` - -```vb -Dim whiteSpaceNodes As Integer - -Dim xmlTree1 As XElement = XElement.Parse(" ", LoadOptions.None) -whiteSpaceNodes = xmlTree1 _ - .DescendantNodesAndSelf() _ - .OfType(Of XText)() _ - .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ - .Count() -Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes) - -Dim xmlTree2 As XElement = XElement.Parse(" ", LoadOptions.PreserveWhitespace) -whiteSpaceNodes = xmlTree2 _ - .DescendantNodesAndSelf() _ - .OfType(Of XText)() _ - .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ - .Count() -Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes) -``` - - This example produces the following output: - -``` -Count of white space nodes (not preserving whitespace): 0 -Count of white space nodes (preserving whitespace): 3 -``` - - The following example retains line information as it parses the string. - -```csharp -string markup = -@" - - - -"; - -XElement xRoot = XElement.Parse(markup, LoadOptions.SetLineInfo); -Console.WriteLine("{0}{1}{2}", - "Element Name".PadRight(20), - "Line".PadRight(5), - "Position"); -Console.WriteLine("{0}{1}{2}", - "------------".PadRight(20), - "----".PadRight(5), - "--------"); -foreach (XElement e in xRoot.DescendantsAndSelf()) - Console.WriteLine("{0}{1}{2}", - ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), - ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), - ((IXmlLineInfo)e).LinePosition); -``` - -```vb -Dim markup As String = _ -"" & Environment.NewLine & _ -" " & Environment.NewLine & _ -" " & Environment.NewLine & _ -" " & Environment.NewLine & _ -"" - -Dim xRoot As XElement = XElement.Parse(markup, LoadOptions.SetLineInfo) -Console.WriteLine("{0}{1}{2}", _ - "Element Name".PadRight(20), _ - "Line".PadRight(5), _ - "Position") -Console.WriteLine("{0}{1}{2}", _ - "------------".PadRight(20), _ - "----".PadRight(5), _ - "--------") -For Each e As XElement In xRoot.DescendantsAndSelf() - Console.WriteLine("{0}{1}{2}", _ - ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString).PadRight(20), _ - DirectCast(e, IXmlLineInfo).LineNumber.ToString().PadRight(5), _ - DirectCast(e, IXmlLineInfo).LinePosition) -Next -``` - - This example produces the following output: - -``` -Element Name Line Position ------------- ---- -------- -Root 1 2 - Child 2 6 - GrandChild 3 10 -``` - + flag in `options` causes the reader to read all white space in the source XML. Nodes of type are created for both significant and insignificant white space. + + If the source XML is indented, not setting the flag in `options` causes the reader to ignore all of the insignificant white space in the source XML. The XML tree is created without any text nodes for insignificant white space. + + If the source XML is not indented, setting the flag in `options` has no effect. Significant white space is still preserved, and there are no spans of insignificant white space that could cause the creation of more white space text nodes. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + Setting will have no effect when parsing from a . + + The may have a valid line information or not. If you set , the line information will be set in the XML tree from the line information that is reported by the . + + There is a performance penalty if you set the flag. + + The line information is accurate immediately after loading the XML document. If you modify the XML tree after loading the document, the line information may become meaningless. + + LINQ to XML's loading functionality is built upon . Therefore, you might catch any exceptions that are thrown by the overload methods and the methods that read and parse the document. + + + +## Examples + The following example parses a string into an in two different ways: preserving white space, and not preserving white space. It then uses a query to determine the number of white space nodes in the resulting XML tree. + +```csharp +int whiteSpaceNodes; + +XElement xmlTree1 = XElement.Parse(" ", + LoadOptions.None); +whiteSpaceNodes = xmlTree1 + .DescendantNodesAndSelf() + .OfType() + .Where(tNode => tNode.ToString().Trim().Length == 0) + .Count(); +Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", + whiteSpaceNodes); + +XElement xmlTree2 = XElement.Parse(" ", + LoadOptions.PreserveWhitespace); +whiteSpaceNodes = xmlTree2 + .DescendantNodesAndSelf() + .OfType() + .Where(tNode => tNode.ToString().Trim().Length == 0) + .Count(); +Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", + whiteSpaceNodes); +``` + +```vb +Dim whiteSpaceNodes As Integer + +Dim xmlTree1 As XElement = XElement.Parse(" ", LoadOptions.None) +whiteSpaceNodes = xmlTree1 _ + .DescendantNodesAndSelf() _ + .OfType(Of XText)() _ + .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ + .Count() +Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes) + +Dim xmlTree2 As XElement = XElement.Parse(" ", LoadOptions.PreserveWhitespace) +whiteSpaceNodes = xmlTree2 _ + .DescendantNodesAndSelf() _ + .OfType(Of XText)() _ + .Where(Function(ByVal tNode As XNode) tNode.ToString().Trim().Length = 0) _ + .Count() +Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes) +``` + + This example produces the following output: + +``` +Count of white space nodes (not preserving whitespace): 0 +Count of white space nodes (preserving whitespace): 3 +``` + + The following example retains line information as it parses the string. + +```csharp +string markup = +@" + + + +"; + +XElement xRoot = XElement.Parse(markup, LoadOptions.SetLineInfo); +Console.WriteLine("{0}{1}{2}", + "Element Name".PadRight(20), + "Line".PadRight(5), + "Position"); +Console.WriteLine("{0}{1}{2}", + "------------".PadRight(20), + "----".PadRight(5), + "--------"); +foreach (XElement e in xRoot.DescendantsAndSelf()) + Console.WriteLine("{0}{1}{2}", + ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20), + ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5), + ((IXmlLineInfo)e).LinePosition); +``` + +```vb +Dim markup As String = _ +"" & Environment.NewLine & _ +" " & Environment.NewLine & _ +" " & Environment.NewLine & _ +" " & Environment.NewLine & _ +"" + +Dim xRoot As XElement = XElement.Parse(markup, LoadOptions.SetLineInfo) +Console.WriteLine("{0}{1}{2}", _ + "Element Name".PadRight(20), _ + "Line".PadRight(5), _ + "Position") +Console.WriteLine("{0}{1}{2}", _ + "------------".PadRight(20), _ + "----".PadRight(5), _ + "--------") +For Each e As XElement In xRoot.DescendantsAndSelf() + Console.WriteLine("{0}{1}{2}", _ + ("".PadRight(e.Ancestors().Count() * 2) & e.Name.ToString).PadRight(20), _ + DirectCast(e, IXmlLineInfo).LineNumber.ToString().PadRight(5), _ + DirectCast(e, IXmlLineInfo).LinePosition) +Next +``` + + This example produces the following output: + +``` +Element Name Line Position +------------ ---- -------- +Root 1 2 + Child 2 6 + GrandChild 3 10 +``` + ]]> LINQ to XML overview @@ -6562,47 +6565,47 @@ Root 1 2 Removes nodes and attributes from this . - and the events. - - - -## Examples - The following example creates an element with attributes and child elements. It then calls this method to remove both the attributes and the child elements. - -```csharp -XElement root = new XElement("Root", - new XAttribute("Att1", 1), - new XAttribute("Att2", 2), - new XAttribute("Att3", 3), - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3) -); -root.RemoveAll(); // removes children elements and attributes of root -Console.WriteLine(root); -``` - -```vb -Dim root As XElement = _ - - 1 - 2 - 3 - - -root.RemoveAll() ' removes children elements and attributes of root -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - -``` - + and the events. + + + +## Examples + The following example creates an element with attributes and child elements. It then calls this method to remove both the attributes and the child elements. + +```csharp +XElement root = new XElement("Root", + new XAttribute("Att1", 1), + new XAttribute("Att2", 2), + new XAttribute("Att3", 3), + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3) +); +root.RemoveAll(); // removes children elements and attributes of root +Console.WriteLine(root); +``` + +```vb +Dim root As XElement = _ + + 1 + 2 + 3 + + +root.RemoveAll() ' removes children elements and attributes of root +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + +``` + ]]> @@ -6647,51 +6650,51 @@ Console.WriteLine(root) Removes the attributes of this . - and the events. - - - -## Examples - The following example creates an element with attributes and child elements. It then calls this method to remove the attributes. The child elements remain. - -```csharp -XElement root = new XElement("Root", - new XAttribute("Att1", 1), - new XAttribute("Att2", 2), - new XAttribute("Att3", 3), - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3) -); -root.RemoveAttributes(); -Console.WriteLine(root); -``` - -```vb -Dim root As XElement = _ - - 1 - 2 - 3 - - -root.RemoveAttributes() -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - - 1 - 2 - 3 - -``` - + and the events. + + + +## Examples + The following example creates an element with attributes and child elements. It then calls this method to remove the attributes. The child elements remain. + +```csharp +XElement root = new XElement("Root", + new XAttribute("Att1", 1), + new XAttribute("Att2", 2), + new XAttribute("Att3", 3), + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3) +); +root.RemoveAttributes(); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement = _ + + 1 + 2 + 3 + + +root.RemoveAttributes() +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + + 1 + 2 + 3 + +``` + ]]> @@ -6708,81 +6711,81 @@ Console.WriteLine(root) Replaces the child nodes and the attributes of this element with the specified content. - and the events. - - - -## Examples - The following example passes the results of a LINQ query to this method, replacing the contents of an element with the query results. It queries the element that is having its contents replaced. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Data", 1), - new XElement("Data", 2), - new XElement("Data", 3), - new XElement("Data", 4), - new XElement("Data", 5) -); - -Console.WriteLine(xmlTree); -Console.WriteLine("-----"); - -xmlTree.ReplaceAll( - from el in xmlTree.Elements() - where (int)el >= 3 - select new XElement("NewData", (int)el) -); - -Console.WriteLine(xmlTree); -``` - -```vb -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Console.WriteLine(xmlTree) -Console.WriteLine("-----") - -xmlTree.ReplaceAll( _ - From el In xmlTree.Elements _ - Where el.Value >= 3 _ - Select <%= el.Value %> _ -) - -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -``` - - 1 - 2 - 3 - 4 - 5 - ------ - - 3 - 4 - 5 - -``` - + and the events. + + + +## Examples + The following example passes the results of a LINQ query to this method, replacing the contents of an element with the query results. It queries the element that is having its contents replaced. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Data", 1), + new XElement("Data", 2), + new XElement("Data", 3), + new XElement("Data", 4), + new XElement("Data", 5) +); + +Console.WriteLine(xmlTree); +Console.WriteLine("-----"); + +xmlTree.ReplaceAll( + from el in xmlTree.Elements() + where (int)el >= 3 + select new XElement("NewData", (int)el) +); + +Console.WriteLine(xmlTree); +``` + +```vb +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Console.WriteLine(xmlTree) +Console.WriteLine("-----") + +xmlTree.ReplaceAll( _ + From el In xmlTree.Elements _ + Where el.Value >= 3 _ + Select <%= el.Value %> _ +) + +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +``` + + 1 + 2 + 3 + 4 + 5 + +----- + + 3 + 4 + 5 + +``` + ]]> LINQ to XML overview @@ -6829,156 +6832,156 @@ Console.WriteLine(xmlTree) The content that will replace the child nodes and attributes of this element. Replaces the child nodes and the attributes of this element with the specified content. - and the events. - - - -## Examples - The following example uses this method. - -```csharp -XElement root = new XElement("Root", - new XElement("Child", "child content") -); - -// ReplaceAll with an XElement object. -root.ReplaceAll(new XElement("NewChild", "n")); -Console.WriteLine(root); - -// ReplaceAll with an XAttribute object. -root.ReplaceAll(new XAttribute("NewAttribute", "n")); -Console.WriteLine(root); - -// ReplaceAll with a string. -root.ReplaceAll("Some text"); -Console.WriteLine(root); - -// ReplaceAll with a double. -double dbl = 12.345; -root.ReplaceAll(dbl); -Console.WriteLine(root); - -// ReplaceAll with a DateTime object. -DateTime dt = new DateTime(2006, 10, 6, 12, 30, 00); -root.ReplaceAll(dt); -Console.WriteLine(root); - -// ReplaceAll with a string array. -// Any collection other than a collection of XElement or XAttribute objects -// are converted to strings. The strings are concatenated and added. -string[] stringArray = { - "abc", - "def", - "ghi" -}; -root.ReplaceAll(stringArray); -Console.WriteLine(root); - -// ReplaceAll with an array of XElement objects. -XElement[] ellArray = { - new XElement("NewChild1", 1), - new XElement("NewChild2", 2), - new XElement("NewChild3", 3) -}; -root.ReplaceAll(ellArray); -Console.WriteLine(root); - -// ReplaceAll with an array of XAttribute objects. -XAttribute[] attArray = { - new XAttribute("NewAtt1", 1), - new XAttribute("NewAtt2", 2), - new XAttribute("NewAtt3", 3) -}; -root.ReplaceAll(attArray); -Console.WriteLine(root); -``` - -```vb -Dim root As XElement = _ - - child content - - -' ReplaceAll with an XElement object. -root.ReplaceAll(n) -Console.WriteLine(root) - -' ReplaceAll with an XAttribute object. -root.ReplaceAll(New XAttribute("NewAttribute", "n")) -Console.WriteLine(root) - -' ReplaceAll with a string. -root.ReplaceAll("Some text") -Console.WriteLine(root) - -' ReplaceAll with a double. -Dim dbl As Double = 12.345 -root.ReplaceAll(dbl) -Console.WriteLine(root) - -' ReplaceAll with a DateTime object. -Dim dt As DateTime = New DateTime(2006, 10, 6, 12, 30, 0) -root.ReplaceAll(dt) -Console.WriteLine(root) - -' ReplaceAll with a string array. -' Any collection other than a collection of XElement or XAttribute objects -' are converted to strings. The strings are concatenated and added. -Dim stringArray As String() = { _ - "abc", _ - "def", _ - "ghi" _ -} -root.ReplaceAll(stringArray) -Console.WriteLine(root) - -' ReplaceAll with an array of XElement objects. -Dim ellArray As XElement() = { _ - New XElement("NewChild1", 1), _ - New XElement("NewChild2", 2), _ - New XElement("NewChild3", 3) _ -} -root.ReplaceAll(ellArray) -Console.WriteLine(root) - -' ReplaceAll with an array of XAttribute objects. -Dim attArray As XAttribute() = { _ -New XAttribute("NewAtt1", 1), _ -New XAttribute("NewAtt2", 2), _ -New XAttribute("NewAtt3", 3) _ -} -root.ReplaceAll(attArray) -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - - n - - -Some text -12.345 -2006-10-06T12:30:00 -abcdefghi - - 1 - 2 - 3 - - -``` - + and the events. + + + +## Examples + The following example uses this method. + +```csharp +XElement root = new XElement("Root", + new XElement("Child", "child content") +); + +// ReplaceAll with an XElement object. +root.ReplaceAll(new XElement("NewChild", "n")); +Console.WriteLine(root); + +// ReplaceAll with an XAttribute object. +root.ReplaceAll(new XAttribute("NewAttribute", "n")); +Console.WriteLine(root); + +// ReplaceAll with a string. +root.ReplaceAll("Some text"); +Console.WriteLine(root); + +// ReplaceAll with a double. +double dbl = 12.345; +root.ReplaceAll(dbl); +Console.WriteLine(root); + +// ReplaceAll with a DateTime object. +DateTime dt = new DateTime(2006, 10, 6, 12, 30, 00); +root.ReplaceAll(dt); +Console.WriteLine(root); + +// ReplaceAll with a string array. +// Any collection other than a collection of XElement or XAttribute objects +// are converted to strings. The strings are concatenated and added. +string[] stringArray = { + "abc", + "def", + "ghi" +}; +root.ReplaceAll(stringArray); +Console.WriteLine(root); + +// ReplaceAll with an array of XElement objects. +XElement[] ellArray = { + new XElement("NewChild1", 1), + new XElement("NewChild2", 2), + new XElement("NewChild3", 3) +}; +root.ReplaceAll(ellArray); +Console.WriteLine(root); + +// ReplaceAll with an array of XAttribute objects. +XAttribute[] attArray = { + new XAttribute("NewAtt1", 1), + new XAttribute("NewAtt2", 2), + new XAttribute("NewAtt3", 3) +}; +root.ReplaceAll(attArray); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement = _ + + child content + + +' ReplaceAll with an XElement object. +root.ReplaceAll(n) +Console.WriteLine(root) + +' ReplaceAll with an XAttribute object. +root.ReplaceAll(New XAttribute("NewAttribute", "n")) +Console.WriteLine(root) + +' ReplaceAll with a string. +root.ReplaceAll("Some text") +Console.WriteLine(root) + +' ReplaceAll with a double. +Dim dbl As Double = 12.345 +root.ReplaceAll(dbl) +Console.WriteLine(root) + +' ReplaceAll with a DateTime object. +Dim dt As DateTime = New DateTime(2006, 10, 6, 12, 30, 0) +root.ReplaceAll(dt) +Console.WriteLine(root) + +' ReplaceAll with a string array. +' Any collection other than a collection of XElement or XAttribute objects +' are converted to strings. The strings are concatenated and added. +Dim stringArray As String() = { _ + "abc", _ + "def", _ + "ghi" _ +} +root.ReplaceAll(stringArray) +Console.WriteLine(root) + +' ReplaceAll with an array of XElement objects. +Dim ellArray As XElement() = { _ + New XElement("NewChild1", 1), _ + New XElement("NewChild2", 2), _ + New XElement("NewChild3", 3) _ +} +root.ReplaceAll(ellArray) +Console.WriteLine(root) + +' ReplaceAll with an array of XAttribute objects. +Dim attArray As XAttribute() = { _ +New XAttribute("NewAtt1", 1), _ +New XAttribute("NewAtt2", 2), _ +New XAttribute("NewAtt3", 3) _ +} +root.ReplaceAll(attArray) +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + + n + + +Some text +12.345 +2006-10-06T12:30:00 +abcdefghi + + 1 + 2 + 3 + + +``` + ]]> LINQ to XML overview @@ -7038,78 +7041,78 @@ Console.WriteLine(root) A parameter list of content objects. Replaces the child nodes and the attributes of this element with the specified content. - and the events. - - - -## Examples - The following example passes the results of a LINQ query to this method, replacing the contents of an element with the query results. - -```csharp -XElement xmlTree1 = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5), - new XElement("Child6", 6) -); - -XElement root = new XElement("Root", - new XElement("Child", "child content") -); - -root.ReplaceAll( - from el in xmlTree1.Elements() - where((int)el >= 3 && (int)el <= 5) - select el -); -Console.WriteLine(root); -``` - -```vb -Dim xmlTree1 As XElement = _ - - 1 - 2 - 3 - 4 - 5 - 6 - - -Dim root As XElement = - child content - - -root.ReplaceAll( _ - From el In xmlTree1.Elements() _ - Where el.Value >= 3 And el.Value <= 5 _ - Select el _ -) - -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - - 3 - 4 - 5 - -``` - + and the events. + + + +## Examples + The following example passes the results of a LINQ query to this method, replacing the contents of an element with the query results. + +```csharp +XElement xmlTree1 = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5), + new XElement("Child6", 6) +); + +XElement root = new XElement("Root", + new XElement("Child", "child content") +); + +root.ReplaceAll( + from el in xmlTree1.Elements() + where((int)el >= 3 && (int)el <= 5) + select el +); +Console.WriteLine(root); +``` + +```vb +Dim xmlTree1 As XElement = _ + + 1 + 2 + 3 + 4 + 5 + 6 + + +Dim root As XElement = + child content + + +root.ReplaceAll( _ + From el In xmlTree1.Elements() _ + Where el.Value >= 3 And el.Value <= 5 _ + Select el _ +) + +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + + 3 + 4 + 5 + +``` + ]]> LINQ to XML overview @@ -7124,42 +7127,42 @@ Console.WriteLine(root) Replaces the attributes of this element with the specified content. - and the events. - - For details about the valid content that can be passed to this function, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - - - -## Examples - The following example creates an element with three attributes. It then uses this method to replace all of the attributes of the element with a single attribute. - -```csharp -XElement root = new XElement("Root", - new XAttribute("Att1", 1), - new XAttribute("Att2", 2), - new XAttribute("Att3", 3) -); -root.ReplaceAttributes( - new XAttribute("NewAtt1", 101) -); -Console.WriteLine(root); -``` - -```vb -Dim root As XElement = -root.ReplaceAttributes(New XAttribute("NewAtt1", 101)) -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - -``` - + and the events. + + For details about the valid content that can be passed to this function, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + + + +## Examples + The following example creates an element with three attributes. It then uses this method to replace all of the attributes of the element with a single attribute. + +```csharp +XElement root = new XElement("Root", + new XAttribute("Att1", 1), + new XAttribute("Att2", 2), + new XAttribute("Att3", 3) +); +root.ReplaceAttributes( + new XAttribute("NewAtt1", 101) +); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement = +root.ReplaceAttributes(New XAttribute("NewAtt1", 101)) +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + +``` + ]]> LINQ to XML overview @@ -7206,44 +7209,44 @@ Console.WriteLine(root) The content that will replace the attributes of this element. Replaces the attributes of this element with the specified content. - and the events. - - - -## Examples - The following example creates an element with three attributes. It then uses this method to replace all of the attributes of the element with a single attribute. - -```csharp -XElement root = new XElement("Root", - new XAttribute("Att1", 1), - new XAttribute("Att2", 2), - new XAttribute("Att3", 3) -); -root.ReplaceAttributes( - new XAttribute("NewAtt1", 101) -); -Console.WriteLine(root); -``` - -```vb -Dim root As XElement = -root.ReplaceAttributes(New XAttribute("NewAtt1", 101)) -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - -``` - + and the events. + + + +## Examples + The following example creates an element with three attributes. It then uses this method to replace all of the attributes of the element with a single attribute. + +```csharp +XElement root = new XElement("Root", + new XAttribute("Att1", 1), + new XAttribute("Att2", 2), + new XAttribute("Att3", 3) +); +root.ReplaceAttributes( + new XAttribute("NewAtt1", 101) +); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement = +root.ReplaceAttributes(New XAttribute("NewAtt1", 101)) +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + +``` + ]]> LINQ to XML overview @@ -7303,49 +7306,49 @@ Console.WriteLine(root) A parameter list of content objects. Replaces the attributes of this element with the specified content. - and the events. - - - -## Examples - The following example creates an element with three attributes. It then replaces the attributes with other attributes. - -```csharp -XElement root = new XElement("Root", - new XAttribute("Att1", 1), - new XAttribute("Att2", 2), - new XAttribute("Att3", 3) -); -root.ReplaceAttributes( - new XAttribute("NewAtt1", 101), - new XAttribute("NewAtt2", 102), - new XAttribute("NewAtt3", 103) -); -Console.WriteLine(root); -``` - -```vb -Dim root As XElement = -root.ReplaceAttributes( _ -New XAttribute("NewAtt1", 101), _ -New XAttribute("NewAtt2", 102), _ -New XAttribute("NewAtt3", 103)) -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml - -``` - + and the events. + + + +## Examples + The following example creates an element with three attributes. It then replaces the attributes with other attributes. + +```csharp +XElement root = new XElement("Root", + new XAttribute("Att1", 1), + new XAttribute("Att2", 2), + new XAttribute("Att3", 3) +); +root.ReplaceAttributes( + new XAttribute("NewAtt1", 101), + new XAttribute("NewAtt2", 102), + new XAttribute("NewAtt3", 103) +); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement = +root.ReplaceAttributes( _ +New XAttribute("NewAtt1", 101), _ +New XAttribute("NewAtt2", 102), _ +New XAttribute("NewAtt3", 103)) +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml + +``` + ]]> LINQ to XML overview @@ -7402,15 +7405,15 @@ Console.WriteLine(root) The stream to output this to. Outputs this to the specified . - that takes as a parameter. Use the option to save unindented XML. This will cause the writer to write all white spaces exactly as represented in the XML tree. - - Use the option if you want to remove duplicate namespace declarations. - + that takes as a parameter. Use the option to save unindented XML. This will cause the writer to write all white spaces exactly as represented in the XML tree. + + Use the option if you want to remove duplicate namespace declarations. + ]]> @@ -7455,43 +7458,43 @@ Console.WriteLine(root) A that the will be written to. Serialize this element to a . - that allows you to specify as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - - -## Examples - The following example creates an , saves the document to a , and then prints the string to the console. - -```csharp -XElement root = XElement.Parse(@" Text "); -using (StringWriter sw = new StringWriter()) { - root.Save(sw); - Console.WriteLine(sw.ToString()); -} -``` - -```vb -Dim root As XElement = Text -Using sw = New StringWriter() - root.Save(sw) - Console.WriteLine(sw.ToString()) -End Using -``` - - This example produces the following output: - -```xml - - - Text - -``` - + that allows you to specify as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + + +## Examples + The following example creates an , saves the document to a , and then prints the string to the console. + +```csharp +XElement root = XElement.Parse(@" Text "); +using (StringWriter sw = new StringWriter()) { + root.Save(sw); + Console.WriteLine(sw.ToString()); +} +``` + +```vb +Dim root As XElement = Text +Using sw = New StringWriter() + root.Save(sw) + Console.WriteLine(sw.ToString()) +End Using +``` + + This example produces the following output: + +```xml + + + Text + +``` + ]]> LINQ to XML overview @@ -7535,46 +7538,46 @@ End Using A that contains the name of the file. Serialize this element to a file. - that allows you to specify as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - - -## Examples - The following example creates an , saves the document to a file, and then prints the file to the console. - -```csharp -XElement root = new XElement("Root", - new XElement("Child", "child content") -); -root.Save("Root.xml"); -string str = File.ReadAllText("Root.xml"); -Console.WriteLine(str); -``` - -```vb -Dim root As XElement = _ - - child content - -root.Save("Root.xml") -Dim Str As String = File.ReadAllText("Root.xml") -Console.WriteLine(Str) -``` - - This example produces the following output: - -```xml - - - child content - -``` - + that allows you to specify as a parameter. For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + + +## Examples + The following example creates an , saves the document to a file, and then prints the file to the console. + +```csharp +XElement root = new XElement("Root", + new XElement("Child", "child content") +); +root.Save("Root.xml"); +string str = File.ReadAllText("Root.xml"); +Console.WriteLine(str); +``` + +```vb +Dim root As XElement = _ + + child content + +root.Save("Root.xml") +Dim Str As String = File.ReadAllText("Root.xml") +Console.WriteLine(Str) +``` + + This example produces the following output: + +```xml + + + child content + +``` + ]]> LINQ to XML overview @@ -7620,43 +7623,43 @@ Console.WriteLine(Str) A that the will be written to. Serialize this element to an . - to an . - -```csharp -StringBuilder sb = new StringBuilder(); -XmlWriterSettings xws = new XmlWriterSettings(); -xws.OmitXmlDeclaration = true; -using (XmlWriter xw = XmlWriter.Create(sb, xws)) { - XElement root = new XElement("Root", - new XElement("Child", "child content") - ); - root.Save(xw); -} -Console.WriteLine(sb.ToString()); -``` - -```vb -Dim sb As StringBuilder = New StringBuilder() -Dim xws As XmlWriterSettings = New XmlWriterSettings() -xws.OmitXmlDeclaration = True -Using xw = XmlWriter.Create(sb, xws) - Dim root As XElement = - child content - - root.Save(xw) -End Using -Console.WriteLine(sb.ToString()) -``` - - This example produces the following output: - -```xml -child content -``` - + to an . + +```csharp +StringBuilder sb = new StringBuilder(); +XmlWriterSettings xws = new XmlWriterSettings(); +xws.OmitXmlDeclaration = true; +using (XmlWriter xw = XmlWriter.Create(sb, xws)) { + XElement root = new XElement("Root", + new XElement("Child", "child content") + ); + root.Save(xw); +} +Console.WriteLine(sb.ToString()); +``` + +```vb +Dim sb As StringBuilder = New StringBuilder() +Dim xws As XmlWriterSettings = New XmlWriterSettings() +xws.OmitXmlDeclaration = True +Using xw = XmlWriter.Create(sb, xws) + Dim root As XElement = + child content + + root.Save(xw) +End Using +Console.WriteLine(sb.ToString()) +``` + + This example produces the following output: + +```xml +child content +``` + ]]> LINQ to XML overview @@ -7703,15 +7706,15 @@ Console.WriteLine(sb.ToString()) A object that specifies formatting behavior. Outputs this to the specified , optionally specifying formatting behavior. - . This option will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. - - If you want to save unindented XML, specify the flag for `options`. This will cause the writer to write all white spaces exactly as represented in the XML tree. - - Use option if you want to remove duplicate namespace declarations. - + . This option will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. + + If you want to save unindented XML, specify the flag for `options`. This will cause the writer to write all white spaces exactly as represented in the XML tree. + + Use option if you want to remove duplicate namespace declarations. + ]]> @@ -7758,65 +7761,65 @@ Console.WriteLine(sb.ToString()) A that specifies formatting behavior. Serialize this element to a , optionally disabling formatting. - flag for `options`. This will cause the writer to write all white space exactly as represented in the XML tree. - - If you want to save indented XML, do not specify the flag for `options`. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the methods that do not take `options` as a parameter. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - - -## Examples - The following example shows two uses of this method. The first use preserves white space. The second serializes the with formatting. Because the document has no white space in it as constructed, preserving white space outputs the XML without any indenting. - -```csharp -XElement root = XElement.Parse(@" Text "); - -using (StringWriter sw = new StringWriter()) -{ - root.Save(sw, SaveOptions.DisableFormatting); - Console.WriteLine(sw.ToString()); -} - -Console.WriteLine("====="); - -using (StringWriter sw = new StringWriter()) -{ - root.Save(sw, SaveOptions.None); - Console.WriteLine(sw.ToString()); -} -``` - -```vb -Dim root As XElement = Text - -Using sw = New StringWriter() - root.Save(sw, SaveOptions.DisableFormatting) - Console.WriteLine(sw.ToString()) -End Using - -Console.WriteLine("=====") - -Using sw = New StringWriter() - root.Save(sw, SaveOptions.None) - Console.WriteLine(sw.ToString()) -End Using -``` - - This example produces the following output: - -``` - Text -===== - - - Text - -``` - + flag for `options`. This will cause the writer to write all white space exactly as represented in the XML tree. + + If you want to save indented XML, do not specify the flag for `options`. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the methods that do not take `options` as a parameter. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + + +## Examples + The following example shows two uses of this method. The first use preserves white space. The second serializes the with formatting. Because the document has no white space in it as constructed, preserving white space outputs the XML without any indenting. + +```csharp +XElement root = XElement.Parse(@" Text "); + +using (StringWriter sw = new StringWriter()) +{ + root.Save(sw, SaveOptions.DisableFormatting); + Console.WriteLine(sw.ToString()); +} + +Console.WriteLine("====="); + +using (StringWriter sw = new StringWriter()) +{ + root.Save(sw, SaveOptions.None); + Console.WriteLine(sw.ToString()); +} +``` + +```vb +Dim root As XElement = Text + +Using sw = New StringWriter() + root.Save(sw, SaveOptions.DisableFormatting) + Console.WriteLine(sw.ToString()) +End Using + +Console.WriteLine("=====") + +Using sw = New StringWriter() + root.Save(sw, SaveOptions.None) + Console.WriteLine(sw.ToString()) +End Using +``` + + This example produces the following output: + +``` + Text +===== + + + Text + +``` + ]]> LINQ to XML overview @@ -7862,61 +7865,61 @@ End Using A that specifies formatting behavior. Serialize this element to a file, optionally disabling formatting. - flag for `options`. This will cause the writer to write all white space exactly as represented in the XML tree. - - If you want to save indented XML, do not specify the flag for `options`. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the methods that do not take `options` as a parameter. - - For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). - - - -## Examples - The following example shows two uses of this method. The first use preserves white space. The second one serializes the with formatting. - -```csharp -string str; -XElement root = XElement.Parse(@" Text "); - -root.Save("Root.xml", SaveOptions.DisableFormatting); -str = File.ReadAllText("Root.xml"); -Console.WriteLine(str); - -Console.WriteLine("====="); - -root.Save("Root.xml", SaveOptions.None); -str = File.ReadAllText("Root.xml"); -Console.WriteLine(str); -``` - -```vb -Dim str As String -Dim root As XElement = Text - -root.Save("Root.xml", SaveOptions.DisableFormatting) -str = File.ReadAllText("Root.xml") -Console.WriteLine(str) - -Console.WriteLine("=====") - -root.Save("Root.xml", SaveOptions.None) -str = File.ReadAllText("Root.xml") -Console.WriteLine(str) -``` - - This example produces the following output: - -``` - Text -===== - - - Text - -``` - + flag for `options`. This will cause the writer to write all white space exactly as represented in the XML tree. + + If you want to save indented XML, do not specify the flag for `options`. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the methods that do not take `options` as a parameter. + + For more information, see [Preserve white space while loading or parsing XML](/dotnet/standard/linq/preserve-white-space-loading-parsing-xml) and [Preserve white space while serializing](/dotnet/standard/linq/preserve-white-space-serializing). + + + +## Examples + The following example shows two uses of this method. The first use preserves white space. The second one serializes the with formatting. + +```csharp +string str; +XElement root = XElement.Parse(@" Text "); + +root.Save("Root.xml", SaveOptions.DisableFormatting); +str = File.ReadAllText("Root.xml"); +Console.WriteLine(str); + +Console.WriteLine("====="); + +root.Save("Root.xml", SaveOptions.None); +str = File.ReadAllText("Root.xml"); +Console.WriteLine(str); +``` + +```vb +Dim str As String +Dim root As XElement = Text + +root.Save("Root.xml", SaveOptions.DisableFormatting) +str = File.ReadAllText("Root.xml") +Console.WriteLine(str) + +Console.WriteLine("=====") + +root.Save("Root.xml", SaveOptions.None) +str = File.ReadAllText("Root.xml") +Console.WriteLine(str) +``` + + This example produces the following output: + +``` + Text +===== + + + Text + +``` + ]]> LINQ to XML overview @@ -7959,6 +7962,7 @@ Console.WriteLine(str) Asynchronously outputs this to an . A task representing the asynchronous save operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -8000,6 +8004,7 @@ Console.WriteLine(str) Asynchronously outputs this to a . A task representing the asynchronous save operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -8041,6 +8046,7 @@ Console.WriteLine(str) Asynchronously outputs this to a . A task representing the asynchronous save operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. @@ -8086,68 +8092,68 @@ Console.WriteLine(str) The value to assign to the attribute. The attribute is removed if the value is . Otherwise, the value is converted to its string representation and assigned to the property of the attribute. Sets the value of an attribute, adds an attribute, or removes an attribute. - and the events. - - The value is assigned to the attribute with the specified name. If no attribute with the specified name exists, a new attribute is added. If the value is `null`, the attribute with the specified name, if any, is deleted. - - For more information, see [Maintain name-value pairs](/dotnet/standard/linq/maintain-name-value-pairs). - - - -## Examples - The following example creates an element with an attribute. It then uses this method to replace the content of the attribute. - -```csharp -// Create an element with no content. -XElement root = new XElement("Root"); - -// Add some name/value pairs. -root.SetAttributeValue("Att1", 1); -root.SetAttributeValue("Att2", 2); -root.SetAttributeValue("Att3", 3); -Console.WriteLine(root); - -// Modify one of the name/value pairs. -root.SetAttributeValue("Att2", 22); -Console.WriteLine(root); - -// Remove one of the name/value pairs. -root.SetAttributeValue("Att3", null); -Console.WriteLine(root); -``` - -```vb -' Create an element with no content. -Dim root As XElement = - -' Add some name/value pairs. -root.SetAttributeValue("Att1", 1) -root.SetAttributeValue("Att2", 2) -root.SetAttributeValue("Att3", 3) -Console.WriteLine(root) - -' Modify one of the name/value pairs. -root.SetAttributeValue("Att2", 22) -Console.WriteLine(root) - -' Remove one of the name/value pairs. -root.SetAttributeValue("Att3", Nothing) -Console.WriteLine(root) -``` - - This example produces the following output: - -``` - - - -``` - + and the events. + + The value is assigned to the attribute with the specified name. If no attribute with the specified name exists, a new attribute is added. If the value is `null`, the attribute with the specified name, if any, is deleted. + + For more information, see [Maintain name-value pairs](/dotnet/standard/linq/maintain-name-value-pairs). + + + +## Examples + The following example creates an element with an attribute. It then uses this method to replace the content of the attribute. + +```csharp +// Create an element with no content. +XElement root = new XElement("Root"); + +// Add some name/value pairs. +root.SetAttributeValue("Att1", 1); +root.SetAttributeValue("Att2", 2); +root.SetAttributeValue("Att3", 3); +Console.WriteLine(root); + +// Modify one of the name/value pairs. +root.SetAttributeValue("Att2", 22); +Console.WriteLine(root); + +// Remove one of the name/value pairs. +root.SetAttributeValue("Att3", null); +Console.WriteLine(root); +``` + +```vb +' Create an element with no content. +Dim root As XElement = + +' Add some name/value pairs. +root.SetAttributeValue("Att1", 1) +root.SetAttributeValue("Att2", 2) +root.SetAttributeValue("Att3", 3) +Console.WriteLine(root) + +' Modify one of the name/value pairs. +root.SetAttributeValue("Att2", 22) +Console.WriteLine(root) + +' Remove one of the name/value pairs. +root.SetAttributeValue("Att3", Nothing) +Console.WriteLine(root) +``` + + This example produces the following output: + +``` + + + +``` + ]]> The is an instance of . @@ -8201,81 +8207,81 @@ Console.WriteLine(root) The value to assign to the child element. The child element is removed if the value is . Otherwise, the value is converted to its string representation and assigned to the property of the child element. Sets the value of a child element, adds a child element, or removes a child element. - is passed as `value`. - - For more information, see [Maintain name-value pairs](/dotnet/standard/linq/maintain-name-value-pairs). - - - -## Examples - The following example creates an element with a child element. It then uses this method to set the value of the child element. - -```csharp -// Create an element with no content -XElement root = new XElement("Root"); - -// Add some name/value pairs. -root.SetElementValue("Ele1", 1); -root.SetElementValue("Ele2", 2); -root.SetElementValue("Ele3", 3); -Console.WriteLine(root); - -// Modify one of the name/value pairs. -root.SetElementValue("Ele2", 22); -Console.WriteLine(root); - -// Remove one of the name/value pairs. -root.SetElementValue("Ele3", null); -Console.WriteLine(root); -``` - -```vb -' Create an element with no content. -Dim root As XElement = - -' Add some name/value pairs. -root.SetElementValue("Ele1", 1) -root.SetElementValue("Ele2", 2) -root.SetElementValue("Ele3", 3) -Console.WriteLine(root) - -' Modify one of the name/value pairs. -root.SetElementValue("Ele2", 22) -Console.WriteLine(root) - -' Remove one of the name/value pairs. -root.SetElementValue("Ele3", Nothing) -Console.WriteLine(root) -``` - - This example produces the following output: - -``` - - 1 - 2 - 3 - - - 1 - 22 - 3 - - - 1 - 22 - -``` - + is passed as `value`. + + For more information, see [Maintain name-value pairs](/dotnet/standard/linq/maintain-name-value-pairs). + + + +## Examples + The following example creates an element with a child element. It then uses this method to set the value of the child element. + +```csharp +// Create an element with no content +XElement root = new XElement("Root"); + +// Add some name/value pairs. +root.SetElementValue("Ele1", 1); +root.SetElementValue("Ele2", 2); +root.SetElementValue("Ele3", 3); +Console.WriteLine(root); + +// Modify one of the name/value pairs. +root.SetElementValue("Ele2", 22); +Console.WriteLine(root); + +// Remove one of the name/value pairs. +root.SetElementValue("Ele3", null); +Console.WriteLine(root); +``` + +```vb +' Create an element with no content. +Dim root As XElement = + +' Add some name/value pairs. +root.SetElementValue("Ele1", 1) +root.SetElementValue("Ele2", 2) +root.SetElementValue("Ele3", 3) +Console.WriteLine(root) + +' Modify one of the name/value pairs. +root.SetElementValue("Ele2", 22) +Console.WriteLine(root) + +' Remove one of the name/value pairs. +root.SetElementValue("Ele3", Nothing) +Console.WriteLine(root) +``` + + This example produces the following output: + +``` + + 1 + 2 + 3 + + + 1 + 22 + 3 + + + 1 + 22 + +``` + ]]> The is an instance of . @@ -8326,42 +8332,42 @@ Console.WriteLine(root) The value to assign to this element. The value is converted to its string representation and assigned to the property. Sets the value of this element. - and the events. - - It is invalid to pass an instance of a class that derives from , such as . - - - -## Examples - The following example creates an element that contains a child element. It then sets the value of the element using this method. - -```csharp -XElement root = new XElement("Root", - new XElement("Child", "child content") -); -root.SetValue("new content"); -Console.WriteLine(root); -``` - -```vb -Dim root As XElement = _ - - child content - - -root.SetValue("new content") -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml -new content -``` - + and the events. + + It is invalid to pass an instance of a class that derives from , such as . + + + +## Examples + The following example creates an element that contains a child element. It then sets the value of the element using this method. + +```csharp +XElement root = new XElement("Root", + new XElement("Child", "child content") +); +root.SetValue("new content"); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement = _ + + child content + + +root.SetValue("new content") +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml +new content +``` + ]]> The is . @@ -8412,13 +8418,13 @@ Console.WriteLine(root) Gets an XML schema definition that describes the XML representation of this object. An that describes the XML representation of the object that is produced by the method and consumed by the method. - interface. - - This method is used internally for serializing object graphs that contain LINQ to XML objects. For an example of serializing an object graph that contains LINQ to XML objects, see [Serialize object graphs that contain XElement objects](/dotnet/standard/linq/serialize-xmlserializer). - + interface. + + This method is used internally for serializing object graphs that contain LINQ to XML objects. For an example of serializing an object graph that contains LINQ to XML objects, see [Serialize object graphs that contain XElement objects](/dotnet/standard/linq/serialize-xmlserializer). + ]]> @@ -8465,13 +8471,13 @@ Console.WriteLine(root) The from which the object is deserialized. Generates an object from its XML representation. - interface. - - This method is used internally for serializing object graphs that contain LINQ to XML objects. For an example of serializing an object graph that contains LINQ to XML objects, see [Serialize object graphs that contain XElement objects](/dotnet/standard/linq/serialize-xmlserializer). - + interface. + + This method is used internally for serializing object graphs that contain LINQ to XML objects. For an example of serializing an object graph that contains LINQ to XML objects, see [Serialize object graphs that contain XElement objects](/dotnet/standard/linq/serialize-xmlserializer). + ]]> @@ -8518,11 +8524,11 @@ Console.WriteLine(root) The to which this object is serialized. Converts an object into its XML representation. - @@ -8564,36 +8570,36 @@ Console.WriteLine(root) Gets or sets the concatenated text contents of this element. A that contains all of the text content of this element. If there are multiple text nodes, they will be concatenated. - and the events. - - If you want to get the value of an element but you are not sure that it exists, it is more convenient to use the explicit conversion operators, and assign the element to a nullable type such as `string` or of . If the element does not exist, the nullable type is set to `null`. By contrast, if you want to use this property, you must make sure that the method does not return `null` before you access this property. - - - -## Examples - The following example uses this property to retrieve the text of an element with mixed content. - -```csharp -XElement el = XElement.Parse("This is mixed content"); -Console.WriteLine("{0}", el.Value); -``` - -```vb -Dim el As XElement = This is mixed content -Console.WriteLine("{0}", el.Value) -``` - - This example produces the following output: - -``` -This is mixed content -``` - + and the events. + + If you want to get the value of an element but you are not sure that it exists, it is more convenient to use the explicit conversion operators, and assign the element to a nullable type such as `string` or of . If the element does not exist, the nullable type is set to `null`. By contrast, if you want to use this property, you must make sure that the method does not return `null` before you access this property. + + + +## Examples + The following example uses this property to retrieve the text of an element with mixed content. + +```csharp +XElement el = XElement.Parse("This is mixed content"); +Console.WriteLine("{0}", el.Value); +``` + +```vb +Dim el As XElement = This is mixed content +Console.WriteLine("{0}", el.Value) +``` + + This example produces the following output: + +``` +This is mixed content +``` + ]]> LINQ to XML overview @@ -8639,73 +8645,73 @@ This is mixed content An into which this method will write. Write this element to an . - to an . Note that the example did not write an XML declaration. - -```csharp -StringBuilder sb = new StringBuilder(); -XmlWriterSettings xws = new XmlWriterSettings(); -xws.OmitXmlDeclaration = true; -xws.Indent = true; - -using (XmlWriter xw = XmlWriter.Create(sb, xws)) { - xw.WriteStartElement("Root"); - - XElement child1 = new XElement("Child", - new XElement("GrandChild", "some content") - ); - child1.WriteTo(xw); - - XElement child2 = new XElement("AnotherChild", - new XElement("GrandChild", "different content") - ); - child2.WriteTo(xw); - - xw.WriteEndElement(); -} - -Console.WriteLine(sb.ToString()); -``` - -```vb -Dim sb As StringBuilder = New StringBuilder() -Dim xws As XmlWriterSettings = New XmlWriterSettings() -xws.OmitXmlDeclaration = True -xws.Indent = True - -Using xw = XmlWriter.Create(sb, xws) - xw.WriteStartElement("Root") - Dim child1 As XElement = _ - - some content - - child1.WriteTo(xw) - Dim child2 As XElement = _ - - different content - - child2.WriteTo(xw) - xw.WriteEndElement() -End Using - -Console.WriteLine(sb.ToString()) -``` - - This example produces the following output: - -```xml - - - some content - - - different content - - -``` - + to an . Note that the example did not write an XML declaration. + +```csharp +StringBuilder sb = new StringBuilder(); +XmlWriterSettings xws = new XmlWriterSettings(); +xws.OmitXmlDeclaration = true; +xws.Indent = true; + +using (XmlWriter xw = XmlWriter.Create(sb, xws)) { + xw.WriteStartElement("Root"); + + XElement child1 = new XElement("Child", + new XElement("GrandChild", "some content") + ); + child1.WriteTo(xw); + + XElement child2 = new XElement("AnotherChild", + new XElement("GrandChild", "different content") + ); + child2.WriteTo(xw); + + xw.WriteEndElement(); +} + +Console.WriteLine(sb.ToString()); +``` + +```vb +Dim sb As StringBuilder = New StringBuilder() +Dim xws As XmlWriterSettings = New XmlWriterSettings() +xws.OmitXmlDeclaration = True +xws.Indent = True + +Using xw = XmlWriter.Create(sb, xws) + xw.WriteStartElement("Root") + Dim child1 As XElement = _ + + some content + + child1.WriteTo(xw) + Dim child2 As XElement = _ + + different content + + child2.WriteTo(xw) + xw.WriteEndElement() +End Using + +Console.WriteLine(sb.ToString()) +``` + + This example produces the following output: + +```xml + + + some content + + + different content + + +``` + ]]> LINQ to XML overview @@ -8748,6 +8754,7 @@ Console.WriteLine(sb.ToString()) Asynchronously writes this to the specified writer. A task representing the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Xml.Linq/XNode.xml b/xml/System.Xml.Linq/XNode.xml index 98ce31c283e..674bbc7ffc3 100644 --- a/xml/System.Xml.Linq/XNode.xml +++ b/xml/System.Xml.Linq/XNode.xml @@ -40,35 +40,35 @@ Represents the abstract concept of a node (element, comment, document type, processing instruction, or text node) in the XML tree. - is an abstract common base class for the following types: - -- - -- - -- - -- - -- - - is an abstract common base class for the following types: - -- - -- - -Objects of classes that derive from can contain child nodes. - + is an abstract common base class for the following types: + +- + +- + +- + +- + +- + + is an abstract common base class for the following types: + +- + +- + +Objects of classes that derive from can contain child nodes. + > [!NOTE] -> An is not an . Attributes are maintained as a list of name/value pairs on an element. - - If you are writing a complex XML application, such as an XML editor or a word processor that stores content as XML, you will often work at the node level. Typical activities when working at the node level include adding nodes, deleting nodes, transforming nodes, and iterating through axes that return collections of nodes. - +> An is not an . Attributes are maintained as a list of name/value pairs on an element. + + If you are writing a complex XML application, such as an XML editor or a word processor that stores content as XML, you will often work at the node level. Typical activities when working at the node level include adding nodes, deleting nodes, transforming nodes, and iterating through axes that return collections of nodes. + ]]> LINQ to XML overview @@ -83,82 +83,82 @@ Objects of classes that derive from can contai Adds the specified content immediately after this node. - and the events. - -## Examples - The following example uses a LINQ query to create an of , which it then passes to this method. This adds the results of a query to the tree in the desired location. - -```csharp -XElement srcTree = new XElement("Root", - new XElement("Element1", 1), - new XElement("Element2", 2), - new XElement("Element3", 3), - new XElement("Element4", 4), - new XElement("Element5", 5) -); -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5) -); -XElement child1 = xmlTree.Element("Child1"); -child1.AddAfterSelf( - from el in srcTree.Elements() - where (int)el > 3 - select el -); -Console.WriteLine(xmlTree); -``` - -```vb -Dim srcTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim child1 As XElement = xmlTree.(0) -child1.AddAfterSelf( _ - From el In srcTree.Elements() _ - Where CInt(el) > 3 _ - Select el _ -) -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - 1 - 4 - 5 - 2 - 3 - 4 - 5 - -``` - + +## Examples + The following example uses a LINQ query to create an of , which it then passes to this method. This adds the results of a query to the tree in the desired location. + +```csharp +XElement srcTree = new XElement("Root", + new XElement("Element1", 1), + new XElement("Element2", 2), + new XElement("Element3", 3), + new XElement("Element4", 4), + new XElement("Element5", 5) +); +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5) +); +XElement child1 = xmlTree.Element("Child1"); +child1.AddAfterSelf( + from el in srcTree.Elements() + where (int)el > 3 + select el +); +Console.WriteLine(xmlTree); +``` + +```vb +Dim srcTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim child1 As XElement = xmlTree.(0) +child1.AddAfterSelf( _ + From el In srcTree.Elements() _ + Where CInt(el) > 3 _ + Select el _ +) +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + 1 + 4 + 5 + 2 + 3 + 4 + 5 + +``` + ]]> LINQ to XML overview @@ -205,59 +205,59 @@ Console.WriteLine(xmlTree) A content object that contains simple content or a collection of content objects to be added after this node. Adds the specified content immediately after this node. - events. - -## Examples - The following example uses this method to add an element into the tree. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5) -); -XElement child1 = xmlTree.Element("Child1"); -child1.AddAfterSelf( - new XElement("NewChild", 10) -); -Console.WriteLine(xmlTree); -``` - -```vb -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim child1 As XElement = xmlTree.(0) -child1.AddAfterSelf(New XElement("NewChild", 10)) -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - 1 - 10 - 2 - 3 - 4 - 5 - -``` - + +## Examples + The following example uses this method to add an element into the tree. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5) +); +XElement child1 = xmlTree.Element("Child1"); +child1.AddAfterSelf( + new XElement("NewChild", 10) +); +Console.WriteLine(xmlTree); +``` + +```vb +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim child1 As XElement = xmlTree.(0) +child1.AddAfterSelf(New XElement("NewChild", 10)) +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + 1 + 10 + 2 + 3 + 4 + 5 + +``` + ]]> The parent is . @@ -318,81 +318,81 @@ Console.WriteLine(xmlTree) A parameter list of content objects. Adds the specified content immediately after this node. - and the events. - -## Examples - The following example uses a LINQ query to create an of , which it then passes to this method. This adds the results of a query to the tree in the desired location. - -```csharp -XElement srcTree = new XElement("Root", - new XElement("Element1", 1), - new XElement("Element2", 2), - new XElement("Element3", 3), - new XElement("Element4", 4), - new XElement("Element5", 5) -); -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5) -); -XElement child1 = xmlTree.Element("Child1"); -child1.AddAfterSelf( - from el in srcTree.Elements() - where (int)el > 3 - select el -); -Console.WriteLine(xmlTree); -``` - -```vb -Dim srcTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim child1 As XElement = xmlTree.(0) -child1.AddAfterSelf( _ - From el In srcTree.Elements() _ - Where CInt(el) > 3 _ - Select el) -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - 1 - 4 - 5 - 2 - 3 - 4 - 5 - -``` - + +## Examples + The following example uses a LINQ query to create an of , which it then passes to this method. This adds the results of a query to the tree in the desired location. + +```csharp +XElement srcTree = new XElement("Root", + new XElement("Element1", 1), + new XElement("Element2", 2), + new XElement("Element3", 3), + new XElement("Element4", 4), + new XElement("Element5", 5) +); +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5) +); +XElement child1 = xmlTree.Element("Child1"); +child1.AddAfterSelf( + from el in srcTree.Elements() + where (int)el > 3 + select el +); +Console.WriteLine(xmlTree); +``` + +```vb +Dim srcTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim child1 As XElement = xmlTree.(0) +child1.AddAfterSelf( _ + From el In srcTree.Elements() _ + Where CInt(el) > 3 _ + Select el) +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + 1 + 4 + 5 + 2 + 3 + 4 + 5 + +``` + ]]> The parent is . @@ -408,84 +408,84 @@ Console.WriteLine(xmlTree) Adds the specified content immediately before this node. - and events. - + and events. + The stores its child notes as a singly-linked list of objects. This means that the method must traverse the list of direct child nodes under the parent container. Therefore, using this method might affect your performance. - -## Examples - The following example uses a LINQ query to create an of , which it then passes to this method. This adds the results of a query to the tree in the desired location. - -```csharp -XElement srcTree = new XElement("Root", - new XElement("Element1", 1), - new XElement("Element2", 2), - new XElement("Element3", 3), - new XElement("Element4", 4), - new XElement("Element5", 5) -); -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5) -); -XElement child1 = xmlTree.Element("Child1"); -child1.AddBeforeSelf( - from el in srcTree.Elements() - where (int)el > 3 - select el -); -Console.WriteLine(xmlTree); -``` - -```vb -Dim srcTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim child1 As XElement = xmlTree.(0) -child1.AddBeforeSelf( _ -From el In srcTree.Elements() _ -Where CInt(el) > 3 _ -Select el) - -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - 4 - 5 - 1 - 2 - 3 - 4 - 5 - -``` - + +## Examples + The following example uses a LINQ query to create an of , which it then passes to this method. This adds the results of a query to the tree in the desired location. + +```csharp +XElement srcTree = new XElement("Root", + new XElement("Element1", 1), + new XElement("Element2", 2), + new XElement("Element3", 3), + new XElement("Element4", 4), + new XElement("Element5", 5) +); +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5) +); +XElement child1 = xmlTree.Element("Child1"); +child1.AddBeforeSelf( + from el in srcTree.Elements() + where (int)el > 3 + select el +); +Console.WriteLine(xmlTree); +``` + +```vb +Dim srcTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim child1 As XElement = xmlTree.(0) +child1.AddBeforeSelf( _ +From el In srcTree.Elements() _ +Where CInt(el) > 3 _ +Select el) + +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + 4 + 5 + 1 + 2 + 3 + 4 + 5 + +``` + ]]> LINQ to XML overview @@ -532,61 +532,61 @@ Console.WriteLine(xmlTree) A content object that contains simple content or a collection of content objects to be added before this node. Adds the specified content immediately before this node. - and the events. - + and the events. + The stores its child nodes as a singly-linked list of objects. This means that the method must traverse the list of direct child nodes under the parent container. Therefore, using this method might affect your performance. - -## Examples - The following example uses this method to add an element into the tree. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5) -); -XElement child1 = xmlTree.Element("Child1"); -child1.AddBeforeSelf( - new XElement("NewChild", 10) -); -Console.WriteLine(xmlTree); -``` - -```vb -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim child1 As XElement = xmlTree.(0) -child1.AddBeforeSelf(New XElement("NewChild", 10)) -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - 10 - 1 - 2 - 3 - 4 - 5 - -``` - + +## Examples + The following example uses this method to add an element into the tree. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5) +); +XElement child1 = xmlTree.Element("Child1"); +child1.AddBeforeSelf( + new XElement("NewChild", 10) +); +Console.WriteLine(xmlTree); +``` + +```vb +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim child1 As XElement = xmlTree.(0) +child1.AddBeforeSelf(New XElement("NewChild", 10)) +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + 10 + 1 + 2 + 3 + 4 + 5 + +``` + ]]> The parent is . @@ -647,84 +647,84 @@ Console.WriteLine(xmlTree) A parameter list of content objects. Adds the specified content immediately before this node. - and the events. - + and the events. + The stores its child nodes as a singly-linked list of objects. This means that the method must traverse the list of direct child nodes under the parent container. Therefore, using this function might affect your performance. - -## Examples - The following example uses a LINQ query to create an of , which it then passes to this method. This adds the results of a query to the tree in the desired location. - -```csharp -XElement srcTree = new XElement("Root", - new XElement("Element1", 1), - new XElement("Element2", 2), - new XElement("Element3", 3), - new XElement("Element4", 4), - new XElement("Element5", 5) -); -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5) -); -XElement child1 = xmlTree.Element("Child1"); -child1.AddBeforeSelf( - from el in srcTree.Elements() - where (int)el > 3 - select el -); -Console.WriteLine(xmlTree); -``` - -```vb -Dim srcTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim child1 As XElement = xmlTree.(0) -child1.AddBeforeSelf( _ - From el In srcTree.Elements() _ - Where CInt(el) > 3 _ - Select el) - -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - 4 - 5 - 1 - 2 - 3 - 4 - 5 - -``` - + +## Examples + The following example uses a LINQ query to create an of , which it then passes to this method. This adds the results of a query to the tree in the desired location. + +```csharp +XElement srcTree = new XElement("Root", + new XElement("Element1", 1), + new XElement("Element2", 2), + new XElement("Element3", 3), + new XElement("Element4", 4), + new XElement("Element5", 5) +); +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5) +); +XElement child1 = xmlTree.Element("Child1"); +child1.AddBeforeSelf( + from el in srcTree.Elements() + where (int)el > 3 + select el +); +Console.WriteLine(xmlTree); +``` + +```vb +Dim srcTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim child1 As XElement = xmlTree.(0) +child1.AddBeforeSelf( _ + From el In srcTree.Elements() _ + Where CInt(el) > 3 _ + Select el) + +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + 4 + 5 + 1 + 2 + 3 + 4 + 5 + +``` + ]]> The parent is . @@ -740,15 +740,15 @@ Console.WriteLine(xmlTree) Returns a collection of the ancestor elements of this node. - LINQ to XML overview @@ -798,50 +798,50 @@ Console.WriteLine(xmlTree) Returns a collection of the ancestor elements of this node. An of of the ancestor elements of this node. - grandChild = xmlTree.Descendants("GrandChild"); -foreach (XElement el in grandChild.Ancestors()) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - - - content - - - -Dim grandChild As IEnumerable(Of XElement) = xmlTree... -For Each el In grandChild.Ancestors() - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -Child -Root -``` - + +## Examples + The following example uses this method to enumerate the ancestors of a node. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child", + new XElement("GrandChild", "content") + ) +); +IEnumerable grandChild = xmlTree.Descendants("GrandChild"); +foreach (XElement el in grandChild.Ancestors()) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + + + content + + + +Dim grandChild As IEnumerable(Of XElement) = xmlTree... +For Each el In grandChild.Ancestors() + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +Child +Root +``` + ]]> LINQ to XML overview @@ -887,51 +887,51 @@ Root The to match. Returns a filtered collection of the ancestor elements of this node. Only elements that have a matching are included in the collection. - An of of the ancestor elements of this node. Only elements that have a matching are included in the collection. - - The nodes in the returned collection are in reverse document order. - + An of of the ancestor elements of this node. Only elements that have a matching are included in the collection. + + The nodes in the returned collection are in reverse document order. + This method uses deferred execution. - grandChild = xmlTree.Descendants("GrandChild"); -foreach (XElement el in grandChild.Ancestors("Child")) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - - - content - - - -Dim grandChild As IEnumerable(Of XElement) = xmlTree... -For Each el In grandChild.Ancestors("Child") - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -Child -``` - + +## Examples + The following example uses this method. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child", + new XElement("GrandChild", "content") + ) +); +IEnumerable grandChild = xmlTree.Descendants("GrandChild"); +foreach (XElement el in grandChild.Ancestors("Child")) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + + + content + + + +Dim grandChild As IEnumerable(Of XElement) = xmlTree... +For Each el In grandChild.Ancestors("Child") + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +Child +``` + ]]> LINQ to XML overview @@ -981,70 +981,70 @@ Child Compares two nodes to determine their relative XML document order. An containing 0 if the nodes are equal; -1 if is before ; 1 if is after . - stores its child nodes as a singly-linked list of objects. This means that the method must traverse the ancestors of the two nodes being compared until it finds the common parent. Then it must traverse the list of the common parent's child nodes to determine the order of the two nodes being compared. Therefore, using this method might affect your performance. - -## Examples - The following example uses this method. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", - new XElement("GrandChild1", 1), - new XElement("GrandChild2", 2), - new XElement("GrandChild3", 3) - ), - new XElement("Child2", - new XElement("GrandChild4", 4), - new XElement("GrandChild5", 5), - new XElement("GrandChild6", 6) - ) -); -XElement el1 = xmlTree.Descendants("GrandChild2").First(); -XElement el2 = xmlTree.Descendants("GrandChild6").First(); -if (XElement.CompareDocumentOrder(el1, el2) == 0) - Console.WriteLine("Compared elements are the same element"); -else if (XElement.CompareDocumentOrder(el1, el2) > 0) - Console.WriteLine("el1 is after el2"); -else - Console.WriteLine("el1 is before el2"); -``` - -```vb -Dim xmlTree As XElement = _ - - - 1 - 2 - 3 - - - 4 - 5 - 6 - - - -Dim el1 As XElement = xmlTree...(0) -Dim el2 As XElement = xmlTree...(0) - -If (XElement.CompareDocumentOrder(el1, el2) = 0) Then - Console.WriteLine("Compared elements are the same element") -ElseIf (XElement.CompareDocumentOrder(el1, el2) > 0) Then - Console.WriteLine("el1 is after el2") -Else - Console.WriteLine("el1 is before el2") -End If -``` - - This example produces the following output: - -``` -el1 is before el2 -``` - + +## Examples + The following example uses this method. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", + new XElement("GrandChild1", 1), + new XElement("GrandChild2", 2), + new XElement("GrandChild3", 3) + ), + new XElement("Child2", + new XElement("GrandChild4", 4), + new XElement("GrandChild5", 5), + new XElement("GrandChild6", 6) + ) +); +XElement el1 = xmlTree.Descendants("GrandChild2").First(); +XElement el2 = xmlTree.Descendants("GrandChild6").First(); +if (XElement.CompareDocumentOrder(el1, el2) == 0) + Console.WriteLine("Compared elements are the same element"); +else if (XElement.CompareDocumentOrder(el1, el2) > 0) + Console.WriteLine("el1 is after el2"); +else + Console.WriteLine("el1 is before el2"); +``` + +```vb +Dim xmlTree As XElement = _ + + + 1 + 2 + 3 + + + 4 + 5 + 6 + + + +Dim el1 As XElement = xmlTree...(0) +Dim el2 As XElement = xmlTree...(0) + +If (XElement.CompareDocumentOrder(el1, el2) = 0) Then + Console.WriteLine("Compared elements are the same element") +ElseIf (XElement.CompareDocumentOrder(el1, el2) > 0) Then + Console.WriteLine("el1 is after el2") +Else + Console.WriteLine("el1 is before el2") +End If +``` + + This example produces the following output: + +``` +el1 is before el2 +``` + ]]> The two nodes do not share a common ancestor. @@ -1100,144 +1100,144 @@ el1 is before el2 Creates an for this node. An that can be used to read this node and its descendants. - . For example, you can create an from a LINQ to XML tree, and then pass that reader to . - - All of the readers returned by are normalizing readers. They always perform line break normalization and full normalization of attributes. In contrast, the returned by is not a normalizing reader. It does not transform any white space. It also returns attributes in the order that they were added, not in attribute name order. - - LINQ to XML does not keep information about whether attributes are default attributes. will always return false regardless of whether the attribute was populated from a default value or not. - - The `PUBLIC` and `SYSTEM` pseudo attributes on are not available through the method. They are only available through the method that takes the qualified name of the attribute as a parameter. If you have to retrieve the `PUBLIC` or `SYSTEM` attributes, you should use the method. - - Base64 and BinHex data are not supported. If you attempt to retrieve these types of data (for example, by calling ), the reader will throw . - + . For example, you can create an from a LINQ to XML tree, and then pass that reader to . + + All of the readers returned by are normalizing readers. They always perform line break normalization and full normalization of attributes. In contrast, the returned by is not a normalizing reader. It does not transform any white space. It also returns attributes in the order that they were added, not in attribute name order. + + LINQ to XML does not keep information about whether attributes are default attributes. will always return false regardless of whether the attribute was populated from a default value or not. + + The `PUBLIC` and `SYSTEM` pseudo attributes on are not available through the method. They are only available through the method that takes the qualified name of the attribute as a parameter. If you have to retrieve the `PUBLIC` or `SYSTEM` attributes, you should use the method. + + Base64 and BinHex data are not supported. If you attempt to retrieve these types of data (for example, by calling ), the reader will throw . + The `xml` declaration is not surfaced by the reader. While reading, you will not encounter a node of type . - -## Examples - The following example creates an XML tree, creates an by using the method, and creates an by using the reader. - -```csharp -XDocument xmlTree = new XDocument( - new XElement("Root", - new XAttribute("Att1", "Attribute Content"), - new XElement("Child1", 1), - new XElement("Child2", 2) - ) -); -XmlReader reader = xmlTree.CreateReader(); -reader.MoveToContent(); -XmlDocument doc = new XmlDocument(); -XmlNode cd = doc.ReadNode(reader); -doc.AppendChild(cd); -Console.WriteLine(doc.OuterXml); -``` - -```vb -Dim xmlTree As XDocument = _ - - - 1 - 2 - -Dim reader As XmlReader = xmlTree.CreateReader() -reader.MoveToContent() -Dim doc As XmlDocument = New XmlDocument() -Dim cd As XmlNode = doc.ReadNode(reader) -doc.AppendChild(cd) -Console.WriteLine(doc.OuterXml) -``` - - This example produces the following output: - -```xml -12 -``` - - Another use for this method is to do an XSLT transformation. You can create an XML tree, create an from the XML tree, create a new document, and create an that will write into the new document. Then, you can invoke the XSLT transformation, passing the and to the transformation. After the transformation successfully completes, the new XML tree is populated with the results of the transform. - -```csharp -string xslMarkup = @" - - - - - - - - - - - -"; - -XDocument xmlTree = new XDocument( - new XElement("Parent", - new XElement("Child1", "Child1 data"), - new XElement("Child2", "Child2 data") - ) -); - -XDocument newTree = new XDocument(); -using (XmlWriter writer = newTree.CreateWriter()) { - // Load the style sheet. - XslCompiledTransform xslt = new XslCompiledTransform(); - xslt.Load(XmlReader.Create(new StringReader(xslMarkup))); - - // Execute the transform and output the results to a writer. - xslt.Transform(xmlTree.CreateReader(), writer); -} - -Console.WriteLine(newTree); -``` - -```vb -Dim xslMarkup As XDocument = _ - - - - - - - - - - - - - - -Dim xmlTree As XElement = _ - - Child1 data - Child2 data - - -Dim newTree As XDocument = New XDocument() - -Using writer As XmlWriter = newTree.CreateWriter() - ' Load the style sheet. - Dim xslt As XslCompiledTransform = _ - New XslCompiledTransform() - xslt.Load(xslMarkup.CreateReader()) - - ' Execute the transform and output the results to a writer. - xslt.Transform(xmlTree.CreateReader(), writer) -End Using - -Console.WriteLine(newTree) -``` - - This example produces the following output: - -```xml - - Child1 data - Child2 data - -``` - + +## Examples + The following example creates an XML tree, creates an by using the method, and creates an by using the reader. + +```csharp +XDocument xmlTree = new XDocument( + new XElement("Root", + new XAttribute("Att1", "Attribute Content"), + new XElement("Child1", 1), + new XElement("Child2", 2) + ) +); +XmlReader reader = xmlTree.CreateReader(); +reader.MoveToContent(); +XmlDocument doc = new XmlDocument(); +XmlNode cd = doc.ReadNode(reader); +doc.AppendChild(cd); +Console.WriteLine(doc.OuterXml); +``` + +```vb +Dim xmlTree As XDocument = _ + + + 1 + 2 + +Dim reader As XmlReader = xmlTree.CreateReader() +reader.MoveToContent() +Dim doc As XmlDocument = New XmlDocument() +Dim cd As XmlNode = doc.ReadNode(reader) +doc.AppendChild(cd) +Console.WriteLine(doc.OuterXml) +``` + + This example produces the following output: + +```xml +12 +``` + + Another use for this method is to do an XSLT transformation. You can create an XML tree, create an from the XML tree, create a new document, and create an that will write into the new document. Then, you can invoke the XSLT transformation, passing the and to the transformation. After the transformation successfully completes, the new XML tree is populated with the results of the transform. + +```csharp +string xslMarkup = @" + + + + + + + + + + + +"; + +XDocument xmlTree = new XDocument( + new XElement("Parent", + new XElement("Child1", "Child1 data"), + new XElement("Child2", "Child2 data") + ) +); + +XDocument newTree = new XDocument(); +using (XmlWriter writer = newTree.CreateWriter()) { + // Load the style sheet. + XslCompiledTransform xslt = new XslCompiledTransform(); + xslt.Load(XmlReader.Create(new StringReader(xslMarkup))); + + // Execute the transform and output the results to a writer. + xslt.Transform(xmlTree.CreateReader(), writer); +} + +Console.WriteLine(newTree); +``` + +```vb +Dim xslMarkup As XDocument = _ + + + + + + + + + + + + + + +Dim xmlTree As XElement = _ + + Child1 data + Child2 data + + +Dim newTree As XDocument = New XDocument() + +Using writer As XmlWriter = newTree.CreateWriter() + ' Load the style sheet. + Dim xslt As XslCompiledTransform = _ + New XslCompiledTransform() + xslt.Load(xslMarkup.CreateReader()) + + ' Execute the transform and output the results to a writer. + xslt.Transform(xmlTree.CreateReader(), writer) +End Using + +Console.WriteLine(newTree) +``` + + This example produces the following output: + +```xml + + Child1 data + Child2 data + +``` + ]]> LINQ to XML overview @@ -1330,68 +1330,68 @@ Console.WriteLine(newTree) if the nodes are equal; otherwise . - objects of different types are never equal. - -- Two nodes are equal if they contain the same text. - -- Two nodes are equal if they have the same tag name, the same set of attributes with the same values, and (ignoring comments and processing instructions) contain two equal length sequences of equal content nodes. - -- Two nodes are equal if their root nodes are equal. - -- Two nodes are equal if they contain the same comment text. - -- Two nodes are equal if they have the same target and data. - + objects of different types are never equal. + +- Two nodes are equal if they contain the same text. + +- Two nodes are equal if they have the same tag name, the same set of attributes with the same values, and (ignoring comments and processing instructions) contain two equal length sequences of equal content nodes. + +- Two nodes are equal if their root nodes are equal. + +- Two nodes are equal if they contain the same comment text. + +- Two nodes are equal if they have the same target and data. + - Two nodes are equal if the have the same name, public ID, system ID, and internal subset. - -## Examples - The following example uses this method to compare two XML trees. - -```csharp -XElement xmlTree1 = new XElement("Root", - new XAttribute("Att1", 1), - new XAttribute("Att2", 2), - new XElement("Child1", 1), - new XElement("Child2", "some content") -); -XElement xmlTree2 = new XElement("Root", - new XAttribute("Att1", 1), - new XAttribute("Att2", 2), - new XElement("Child1", 1), - new XElement("Child2", "some content") -); -Console.WriteLine(XNode.DeepEquals(xmlTree1, xmlTree2)); -``` - -```vb -Dim xmlTree1 As XElement = _ - - 1 - some content - - -Dim xmlTree2 As XElement = _ - - 1 - some content - - -Console.WriteLine(XNode.DeepEquals(xmlTree1, xmlTree2)) -``` - - This example produces the following output: - -``` -True -``` - + +## Examples + The following example uses this method to compare two XML trees. + +```csharp +XElement xmlTree1 = new XElement("Root", + new XAttribute("Att1", 1), + new XAttribute("Att2", 2), + new XElement("Child1", 1), + new XElement("Child2", "some content") +); +XElement xmlTree2 = new XElement("Root", + new XAttribute("Att1", 1), + new XAttribute("Att2", 2), + new XElement("Child1", 1), + new XElement("Child2", "some content") +); +Console.WriteLine(XNode.DeepEquals(xmlTree1, xmlTree2)); +``` + +```vb +Dim xmlTree1 As XElement = _ + + 1 + some content + + +Dim xmlTree2 As XElement = _ + + 1 + some content + + +Console.WriteLine(XNode.DeepEquals(xmlTree1, xmlTree2)) +``` + + This example produces the following output: + +``` +True +``` + ]]> LINQ to XML overview @@ -1434,66 +1434,66 @@ True Gets a comparer that can compare the relative position of two nodes. An that can compare the relative position of two nodes. - extension method. The recommended approach is to use that extension method instead of using this property directly. - -## Examples - The following example creates an XML tree with some elements. It then creates a of that contains some elements from the XML tree at random. It sorts the list, using this property to retrieve a , which implements the and interfaces. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5) -); - -List nodeList = new List(); -nodeList.Add(xmlTree.Element("Child5")); -nodeList.Add(xmlTree.Element("Child3")); -nodeList.Add(xmlTree.Element("Child1")); - -// Sort nodes in document order. -nodeList.Sort(XNode.DocumentOrderComparer); - -foreach (XElement el in nodeList) - Console.WriteLine(el); -``` - -```vb -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim nodeList As List(Of XNode) = New List(Of XNode)() -nodeList.Add(xmlTree.Element("Child5")) -nodeList.Add(xmlTree.Element("Child3")) -nodeList.Add(xmlTree.Element("Child1")) - -' Sort nodes in document order. -nodeList.Sort(XNode.DocumentOrderComparer) - -For Each el In nodeList - Console.WriteLine(el) -Next -``` - - This example produces the following output: - -``` -1 -3 -5 -``` - + +## Examples + The following example creates an XML tree with some elements. It then creates a of that contains some elements from the XML tree at random. It sorts the list, using this property to retrieve a , which implements the and interfaces. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5) +); + +List nodeList = new List(); +nodeList.Add(xmlTree.Element("Child5")); +nodeList.Add(xmlTree.Element("Child3")); +nodeList.Add(xmlTree.Element("Child1")); + +// Sort nodes in document order. +nodeList.Sort(XNode.DocumentOrderComparer); + +foreach (XElement el in nodeList) + Console.WriteLine(el); +``` + +```vb +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim nodeList As List(Of XNode) = New List(Of XNode)() +nodeList.Add(xmlTree.Element("Child5")) +nodeList.Add(xmlTree.Element("Child3")) +nodeList.Add(xmlTree.Element("Child1")) + +' Sort nodes in document order. +nodeList.Sort(XNode.DocumentOrderComparer) + +For Each el In nodeList + Console.WriteLine(el) +Next +``` + + This example produces the following output: + +``` +1 +3 +5 +``` + ]]> LINQ to XML overview @@ -1508,11 +1508,11 @@ Next Returns a collection of the sibling elements after this node, in document order. - LINQ to XML overview @@ -1562,56 +1562,56 @@ Next Returns a collection of the sibling elements after this node, in document order. An of of the sibling elements after this node, in document order. - elements = child.ElementsAfterSelf(); -foreach (XElement el in elements) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - Text content. - child1 content - child2 content - child3 contentMore text content. - child4 content - child5 content - - -Dim child As XElement = xmlTree.(0) -Dim elements As IEnumerable(Of XElement) = child.ElementsAfterSelf() -For Each el In elements - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -Child4 -Child5 -``` - + +## Examples + The following example creates an element with some complex content. It then uses this method to retrieve the nodes in document order. + +```csharp +XElement xmlTree = new XElement("Root", + new XText("Text content."), + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XElement("Child3", "child3 content"), + new XText("More text content."), + new XElement("Child4", "child4 content"), + new XElement("Child5", "child5 content") +); +XElement child = xmlTree.Element("Child3"); +IEnumerable elements = child.ElementsAfterSelf(); +foreach (XElement el in elements) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + Text content. + child1 content + child2 content + child3 contentMore text content. + child4 content + child5 content + + +Dim child As XElement = xmlTree.(0) +Dim elements As IEnumerable(Of XElement) = child.ElementsAfterSelf() +For Each el In elements + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +Child4 +Child5 +``` + ]]> LINQ to XML overview @@ -1659,56 +1659,56 @@ Child5 Returns a filtered collection of the sibling elements after this node, in document order. Only elements that have a matching are included in the collection. An of of the sibling elements after this node, in document order. Only elements that have a matching are included in the collection. - elements = child.ElementsAfterSelf("Child4"); -foreach (XElement el in elements) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - Text content. - child1 content - child2 content - child3 contentMore text content. - child4 content - child5 content - - -Dim child As XElement = xmlTree.(0) -Dim elements As IEnumerable(Of XElement) = child.ElementsAfterSelf("Child4") - -For Each el In elements - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -Child4 -``` - + +## Examples + The following example creates an element with some complex content. It then uses this method to retrieve the sibling elements, in document order. + +```csharp +XElement xmlTree = new XElement("Root", + new XText("Text content."), + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XElement("Child3", "child3 content"), + new XText("More text content."), + new XElement("Child4", "child4 content"), + new XElement("Child5", "child5 content") +); +XElement child = xmlTree.Element("Child3"); +IEnumerable elements = child.ElementsAfterSelf("Child4"); +foreach (XElement el in elements) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + Text content. + child1 content + child2 content + child3 contentMore text content. + child4 content + child5 content + + +Dim child As XElement = xmlTree.(0) +Dim elements As IEnumerable(Of XElement) = child.ElementsAfterSelf("Child4") + +For Each el In elements + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +Child4 +``` + ]]> LINQ to XML overview @@ -1723,11 +1723,11 @@ Child4 Returns a collection of the sibling elements before this node, in document order. - LINQ to XML overview @@ -1777,57 +1777,57 @@ Child4 Returns a collection of the sibling elements before this node, in document order. An of of the sibling elements before this node, in document order. - elements = child.ElementsBeforeSelf(); -foreach (XElement el in elements) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - Text content. - child1 content - child2 content - child3 contentMore text content. - child4 content - child5 content - - -Dim child As XElement = xmlTree.(0) -Dim elements As IEnumerable(Of XElement) = child.ElementsBeforeSelf() - -For Each el In elements - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -Child1 -Child2 -``` - + +## Examples + The following example uses this axis method. + +```csharp +XElement xmlTree = new XElement("Root", + new XText("Text content."), + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XElement("Child3", "child3 content"), + new XText("More text content."), + new XElement("Child4", "child4 content"), + new XElement("Child5", "child5 content") +); +XElement child = xmlTree.Element("Child3"); +IEnumerable elements = child.ElementsBeforeSelf(); +foreach (XElement el in elements) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + Text content. + child1 content + child2 content + child3 contentMore text content. + child4 content + child5 content + + +Dim child As XElement = xmlTree.(0) +Dim elements As IEnumerable(Of XElement) = child.ElementsBeforeSelf() + +For Each el In elements + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +Child1 +Child2 +``` + ]]> LINQ to XML overview @@ -1875,56 +1875,56 @@ Child2 Returns a filtered collection of the sibling elements before this node, in document order. Only elements that have a matching are included in the collection. An of of the sibling elements before this node, in document order. Only elements that have a matching are included in the collection. - elements = child.ElementsBeforeSelf("Child2"); -foreach (XElement el in elements) - Console.WriteLine(el.Name); -``` - -```vb -Dim xmlTree As XElement = _ - Text content. - child1 content - child2 content - child3 contentMore text content. - child4 content - child5 content - - -Dim child As XElement = xmlTree.(0) -Dim elements As IEnumerable(Of XElement) = child.ElementsBeforeSelf("Child2") - -For Each el In elements - Console.WriteLine(el.Name) -Next -``` - - This example produces the following output: - -``` -Child2 -``` - + +## Examples + The following example uses this method. + +```csharp +XElement xmlTree = new XElement("Root", + new XText("Text content."), + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XElement("Child3", "child3 content"), + new XText("More text content."), + new XElement("Child4", "child4 content"), + new XElement("Child5", "child5 content") +); +XElement child = xmlTree.Element("Child3"); +IEnumerable elements = child.ElementsBeforeSelf("Child2"); +foreach (XElement el in elements) + Console.WriteLine(el.Name); +``` + +```vb +Dim xmlTree As XElement = _ + Text content. + child1 content + child2 content + child3 contentMore text content. + child4 content + child5 content + + +Dim child As XElement = xmlTree.(0) +Dim elements As IEnumerable(Of XElement) = child.ElementsBeforeSelf("Child2") + +For Each el In elements + Console.WriteLine(el.Name) +Next +``` + + This example produces the following output: + +``` +Child2 +``` + ]]> LINQ to XML overview @@ -1967,54 +1967,54 @@ Child2 Gets a comparer that can compare two nodes for value equality. A that can compare two nodes for value equality. - , which implements the and interfaces. It creates a dictionary that uses this property. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5) -); - -Dictionary nodeDictionary = new Dictionary(XNode.EqualityComparer); -nodeDictionary.Add(xmlTree.Element("Child5"), "Child 5 Information"); -nodeDictionary.Add(xmlTree.Element("Child3"), "Child 3 Information"); -nodeDictionary.Add(xmlTree.Element("Child1"), "Child 1 Information"); - -string str = nodeDictionary[xmlTree.Element("Child3")]; -Console.WriteLine(str); -``` - -```vb -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim nodeDictionary As Dictionary(Of XNode, String) = New Dictionary(Of XNode, String)(XNode.EqualityComparer) -nodeDictionary.Add(xmlTree.Element("Child5"), "Child 5 Information") -nodeDictionary.Add(xmlTree.Element("Child3"), "Child 3 Information") -nodeDictionary.Add(xmlTree.Element("Child1"), "Child 1 Information") - -Dim str As String = nodeDictionary(xmlTree.Element("Child3")) -Console.WriteLine(str) -``` - - This example produces the following output: - -``` -Child 3 Information -``` - + , which implements the and interfaces. It creates a dictionary that uses this property. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5) +); + +Dictionary nodeDictionary = new Dictionary(XNode.EqualityComparer); +nodeDictionary.Add(xmlTree.Element("Child5"), "Child 5 Information"); +nodeDictionary.Add(xmlTree.Element("Child3"), "Child 3 Information"); +nodeDictionary.Add(xmlTree.Element("Child1"), "Child 1 Information"); + +string str = nodeDictionary[xmlTree.Element("Child3")]; +Console.WriteLine(str); +``` + +```vb +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim nodeDictionary As Dictionary(Of XNode, String) = New Dictionary(Of XNode, String)(XNode.EqualityComparer) +nodeDictionary.Add(xmlTree.Element("Child5"), "Child 5 Information") +nodeDictionary.Add(xmlTree.Element("Child3"), "Child 3 Information") +nodeDictionary.Add(xmlTree.Element("Child1"), "Child 1 Information") + +Dim str As String = nodeDictionary(xmlTree.Element("Child3")) +Console.WriteLine(str) +``` + + This example produces the following output: + +``` +Child 3 Information +``` + ]]> LINQ to XML overview @@ -2063,57 +2063,57 @@ Child 3 Information if this node appears after the specified node; otherwise . - stores its child nodes as a singly-linked list of objects. This means that the method must traverse the ancestors of the two nodes being compared until it finds the common parent. Then it must traverse the list of the common parent's child nodes to determine the order of the two nodes being compared. Therefore, using this method might affect your performance. - -## Examples - The following example uses this method. - -```csharp -XElement xmlTree = new XElement("Root", - new XText("Text content."), - new XElement("Child1", "child1 content"), - new XElement("Child2", "child2 content"), - new XElement("Child3", "child3 content"), - new XText("More text content."), - new XElement("Child4", "child4 content"), - new XElement("Child5", "child5 content") -); -XElement child3 = xmlTree.Element("Child3"); -XElement child5 = xmlTree.Element("Child5"); -if (child5.IsAfter(child3)) - Console.WriteLine("Child5 is after Child3"); -else - Console.WriteLine("Child5 is not after Child3"); -``` - -```vb -Dim xmlTree As XElement = _ - Text content. - child1 content - child2 content - child3 contentMore text content. - child4 content - child5 content - - -Dim child3 As XElement = xmlTree.(0) -Dim child5 As XElement = xmlTree.(0) -If (child5.IsAfter(child3)) Then - Console.WriteLine("Child5 is after Child3") -Else - Console.WriteLine("Child5 is not after Child3") -End If -``` - - This example produces the following output: - -``` -Child5 is after Child3 -``` - + +## Examples + The following example uses this method. + +```csharp +XElement xmlTree = new XElement("Root", + new XText("Text content."), + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XElement("Child3", "child3 content"), + new XText("More text content."), + new XElement("Child4", "child4 content"), + new XElement("Child5", "child5 content") +); +XElement child3 = xmlTree.Element("Child3"); +XElement child5 = xmlTree.Element("Child5"); +if (child5.IsAfter(child3)) + Console.WriteLine("Child5 is after Child3"); +else + Console.WriteLine("Child5 is not after Child3"); +``` + +```vb +Dim xmlTree As XElement = _ + Text content. + child1 content + child2 content + child3 contentMore text content. + child4 content + child5 content + + +Dim child3 As XElement = xmlTree.(0) +Dim child5 As XElement = xmlTree.(0) +If (child5.IsAfter(child3)) Then + Console.WriteLine("Child5 is after Child3") +Else + Console.WriteLine("Child5 is not after Child3") +End If +``` + + This example produces the following output: + +``` +Child5 is after Child3 +``` + ]]> LINQ to XML overview @@ -2162,57 +2162,57 @@ Child5 is after Child3 if this node appears before the specified node; otherwise . - stores its child nodes as a singly-linked list of objects. This means that the method must traverse the ancestors of the two nodes being compared until it finds the common parent. Then it must traverse the list of the common parent's child nodes to determine the order of the two nodes being compared. Therefore, using this method might affect your performance. - -## Examples - The following example uses this method. - -```csharp -XElement xmlTree = new XElement("Root", - new XText("Text content."), - new XElement("Child1", "child1 content"), - new XElement("Child2", "child2 content"), - new XElement("Child3", "child3 content"), - new XText("More text content."), - new XElement("Child4", "child4 content"), - new XElement("Child5", "child5 content") -); -XElement child3 = xmlTree.Element("Child3"); -XElement child5 = xmlTree.Element("Child5"); -if (child5.IsBefore(child3)) - Console.WriteLine("Child5 is before Child3"); -else - Console.WriteLine("Child5 is not before Child3"); -``` - -```vb -Dim xmlTree As XElement = _ - Text content. - child1 content - child2 content - child3 contentMore text content. - child4 content - child5 content - - -Dim child3 As XElement = xmlTree.(0) -Dim child5 As XElement = xmlTree.(0) -If (child5.IsBefore(child3)) Then - Console.WriteLine("Child5 is before Child3") -Else - Console.WriteLine("Child5 is not before Child3") -End If -``` - - This example produces the following output: - -``` -Child5 is not before Child3 -``` - + +## Examples + The following example uses this method. + +```csharp +XElement xmlTree = new XElement("Root", + new XText("Text content."), + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XElement("Child3", "child3 content"), + new XText("More text content."), + new XElement("Child4", "child4 content"), + new XElement("Child5", "child5 content") +); +XElement child3 = xmlTree.Element("Child3"); +XElement child5 = xmlTree.Element("Child5"); +if (child5.IsBefore(child3)) + Console.WriteLine("Child5 is before Child3"); +else + Console.WriteLine("Child5 is not before Child3"); +``` + +```vb +Dim xmlTree As XElement = _ + Text content. + child1 content + child2 content + child3 contentMore text content. + child4 content + child5 content + + +Dim child3 As XElement = xmlTree.(0) +Dim child5 As XElement = xmlTree.(0) +If (child5.IsBefore(child3)) Then + Console.WriteLine("Child5 is before Child3") +Else + Console.WriteLine("Child5 is not before Child3") +End If +``` + + This example produces the following output: + +``` +Child5 is not before Child3 +``` + ]]> LINQ to XML overview @@ -2256,83 +2256,83 @@ Child5 is not before Child3 Gets the next sibling node of this node. The that contains the next sibling node. - does not have a parent, or if there is no next node, this property returns `null`. - -## Examples - The following example uses this property to loop through nodes. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XText("Some Text"), - new XElement("Child2", - 2, - new XElement("GrandChild", "GrandChild Content") - ), - new XComment("a comment"), - new XElement("Child3") -); -XNode node = xmlTree.Element("Child2"); -do { - StringBuilder sb = new StringBuilder(); - sb.Append(String.Format("NodeType: {0}", node.NodeType.ToString().PadRight(10))); - switch (node.NodeType) - { - case XmlNodeType.Text: - sb.Append((node as XText).Value); - break; - case XmlNodeType.Element: - sb.Append((node as XElement).Name); - break; - case XmlNodeType.Comment: - sb.Append((node as XComment).Value); - break; - } - Console.WriteLine(sb.ToString()); -} -while ((node = node.NextNode) != null); -``` - -```vb -Dim xmlTree As XElement = _ - - 1Some Text - 2 - GrandChild Content - - - 3 - - -Dim node As XNode = xmlTree.Element("Child2") -Do - Dim sb As StringBuilder = New StringBuilder() - sb.Append(String.Format("NodeType: {0}", node.NodeType.ToString().PadRight(10))) - Select Case node.NodeType - Case XmlNodeType.Text - sb.Append(DirectCast(node, XText).Value) - Case XmlNodeType.Element - sb.Append(DirectCast(node, XElement).Name) - Case XmlNodeType.Comment - sb.Append(DirectCast(node, XComment).Value) - End Select - Console.WriteLine(sb.ToString()) - - node = node.NextNode -Loop While (Not (node Is Nothing)) -``` - - This example produces the following output: - -``` -NodeType: Element Child2 -NodeType: Comment a comment -NodeType: Element Child3 -``` - + +## Examples + The following example uses this property to loop through nodes. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XText("Some Text"), + new XElement("Child2", + 2, + new XElement("GrandChild", "GrandChild Content") + ), + new XComment("a comment"), + new XElement("Child3") +); +XNode node = xmlTree.Element("Child2"); +do { + StringBuilder sb = new StringBuilder(); + sb.Append(String.Format("NodeType: {0}", node.NodeType.ToString().PadRight(10))); + switch (node.NodeType) + { + case XmlNodeType.Text: + sb.Append((node as XText).Value); + break; + case XmlNodeType.Element: + sb.Append((node as XElement).Name); + break; + case XmlNodeType.Comment: + sb.Append((node as XComment).Value); + break; + } + Console.WriteLine(sb.ToString()); +} +while ((node = node.NextNode) != null); +``` + +```vb +Dim xmlTree As XElement = _ + + 1Some Text + 2 + GrandChild Content + + + 3 + + +Dim node As XNode = xmlTree.Element("Child2") +Do + Dim sb As StringBuilder = New StringBuilder() + sb.Append(String.Format("NodeType: {0}", node.NodeType.ToString().PadRight(10))) + Select Case node.NodeType + Case XmlNodeType.Text + sb.Append(DirectCast(node, XText).Value) + Case XmlNodeType.Element + sb.Append(DirectCast(node, XElement).Name) + Case XmlNodeType.Comment + sb.Append(DirectCast(node, XComment).Value) + End Select + Console.WriteLine(sb.ToString()) + + node = node.NextNode +Loop While (Not (node Is Nothing)) +``` + + This example produces the following output: + +``` +NodeType: Element Child2 +NodeType: Comment a comment +NodeType: Element Child3 +``` + ]]> LINQ to XML overview @@ -2387,64 +2387,64 @@ NodeType: Element Child3 Returns a collection of the sibling nodes after this node, in document order. An of of the sibling nodes after this node, in document order. - nodes = - from node in child.NodesAfterSelf() - select node; -foreach (XNode node in nodes) -{ - Console.WriteLine("Node type: {0} {1}", - node.NodeType, - node.NodeType == XmlNodeType.Text ? (node as XText).Value : ""); -} -``` - -```vb -Dim xmlTree As XElement = New XElement("Root", _New XText("Text content."), _ - New XElement("Child1", "child1 content"), _ - New XElement("Child2", "child2 content"), _ - New XText("More text content."), _ - New XElement("child3", "child3 content") _ -) - -Dim child As XElement = xmlTree.Element("Child2") -Dim nodes As IEnumerable(Of XNode) = _ - From node In child.NodesAfterSelf() _ - Select node -For Each node As XNode In nodes - Dim s As String = "" - If node.NodeType = XmlNodeType.Text Then - s = DirectCast(node, XText).Value - End If - Console.WriteLine("Node type: {0} {1}", node.NodeType, s) -Next -``` - - This example produces the following output: - -``` -Node type: Text More text content. -Node type: Element -``` - + +## Examples + The following example creates an XML tree, and then queries the tree using this axis method. + +```csharp +XElement xmlTree = new XElement("Root", + new XText("Text content."), + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XText("More text content."), + new XElement("child3", "child3 content") +); +XElement child = xmlTree.Element("Child2"); +IEnumerable nodes = + from node in child.NodesAfterSelf() + select node; +foreach (XNode node in nodes) +{ + Console.WriteLine("Node type: {0} {1}", + node.NodeType, + node.NodeType == XmlNodeType.Text ? (node as XText).Value : ""); +} +``` + +```vb +Dim xmlTree As XElement = New XElement("Root", _New XText("Text content."), _ + New XElement("Child1", "child1 content"), _ + New XElement("Child2", "child2 content"), _ + New XText("More text content."), _ + New XElement("child3", "child3 content") _ +) + +Dim child As XElement = xmlTree.Element("Child2") +Dim nodes As IEnumerable(Of XNode) = _ + From node In child.NodesAfterSelf() _ + Select node +For Each node As XNode In nodes + Dim s As String = "" + If node.NodeType = XmlNodeType.Text Then + s = DirectCast(node, XText).Value + End If + Console.WriteLine("Node type: {0} {1}", node.NodeType, s) +Next +``` + + This example produces the following output: + +``` +Node type: Text More text content. +Node type: Element +``` + ]]> LINQ to XML overview @@ -2499,63 +2499,63 @@ Node type: Element Returns a collection of the sibling nodes before this node, in document order. An of of the sibling nodes before this node, in document order. - nodes = - from node in child.NodesBeforeSelf() - select node; -foreach (XNode node in nodes) - Console.WriteLine("Node type: {0} {1}", - node.NodeType, - node.NodeType == XmlNodeType.Text ? (node as XText).Value : ""); -``` - -```vb -Dim xmlTree As XElement = New XElement("Root", _ - New XText("Text content."), _ - New XElement("Child1", "child1 content"), _ - New XElement("Child2", "child2 content"), _ - New XText("More text content."), _ - New XElement("child3", "child3 content") _ -) - -Dim child As XElement = xmlTree.Element("Child2") -Dim nodes As IEnumerable(Of XNode) = _ - From node In child.NodesBeforeSelf() _ - Select node -For Each node As XNode In nodes - Dim s As String = "" - If node.NodeType = XmlNodeType.Text Then - s = DirectCast(node, XText).Value - End If - Console.WriteLine("Node type: {0} {1}", node.NodeType, s) -Next -``` - - This example produces the following output: - -``` -Node type: Text Text content. -Node type: Element -``` - + +## Examples + The following example creates an XML tree, and then queries the tree using this axis method. + +```csharp +XElement xmlTree = new XElement("Root", + new XText("Text content."), + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XText("More text content."), + new XElement("child3", "child3 content") +); +XElement child = xmlTree.Element("Child2"); +IEnumerable nodes = + from node in child.NodesBeforeSelf() + select node; +foreach (XNode node in nodes) + Console.WriteLine("Node type: {0} {1}", + node.NodeType, + node.NodeType == XmlNodeType.Text ? (node as XText).Value : ""); +``` + +```vb +Dim xmlTree As XElement = New XElement("Root", _ + New XText("Text content."), _ + New XElement("Child1", "child1 content"), _ + New XElement("Child2", "child2 content"), _ + New XText("More text content."), _ + New XElement("child3", "child3 content") _ +) + +Dim child As XElement = xmlTree.Element("Child2") +Dim nodes As IEnumerable(Of XNode) = _ + From node In child.NodesBeforeSelf() _ + Select node +For Each node As XNode In nodes + Dim s As String = "" + If node.NodeType = XmlNodeType.Text Then + s = DirectCast(node, XText).Value + End If + Console.WriteLine("Node type: {0} {1}", node.NodeType, s) +Next +``` + + This example produces the following output: + +``` +Node type: Text Text content. +Node type: Element +``` + ]]> LINQ to XML overview @@ -2599,84 +2599,84 @@ Node type: Element Gets the previous sibling node of this node. The that contains the previous sibling node. - does not have a parent, or if there is no previous node, this property returns `null`. - + does not have a parent, or if there is no previous node, this property returns `null`. + The stores its child nodes as a singly-linked list of objects. This means that the property must traverse the list of direct child nodes under the parent container. Therefore, using this property might affect your performance. - -## Examples - The following example uses this property to loop through nodes. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XText("Some Text"), - new XElement("Child2", - 2, - new XElement("GrandChild", "GrandChild Content") - ), - new XComment("a comment"), - new XElement("Child3") -); -XNode node = xmlTree.Element("Child2"); -do { - StringBuilder sb = new StringBuilder(); - sb.Append(String.Format("NodeType: {0}", node.NodeType.ToString().PadRight(10))); - switch (node.NodeType) - { - case XmlNodeType.Text: - sb.Append((node as XText).Value); - break; - case XmlNodeType.Element: - sb.Append((node as XElement).Name); - break; - case XmlNodeType.Comment: - sb.Append((node as XComment).Value); - break; - } - Console.WriteLine(sb.ToString()); -} -while ((node = node.PreviousNode) != null); -``` - -```vb -Dim xmlTree As XElement = _ - - 1Some Text2 - GrandChild Content - - - 3 - - -Dim node As XNode = xmlTree.Element("Child2") -Do - Dim sb As StringBuilder = New StringBuilder() - sb.Append(String.Format("NodeType: {0}", node.NodeType.ToString().PadRight(10))) - Select Case node.NodeType - Case XmlNodeType.Text - sb.Append(DirectCast(node, XText).Value) - Case XmlNodeType.Element - sb.Append(DirectCast(node, XElement).Name) - Case XmlNodeType.Comment - sb.Append(DirectCast(node, XComment).Value) - End Select - Console.WriteLine(sb.ToString()) - - node = node.PreviousNode -Loop While (Not (node Is Nothing)) -``` - - This example produces the following output: - -``` -NodeType: Element Child2 -NodeType: Text Some Text -NodeType: Element Child1 -``` - + +## Examples + The following example uses this property to loop through nodes. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XText("Some Text"), + new XElement("Child2", + 2, + new XElement("GrandChild", "GrandChild Content") + ), + new XComment("a comment"), + new XElement("Child3") +); +XNode node = xmlTree.Element("Child2"); +do { + StringBuilder sb = new StringBuilder(); + sb.Append(String.Format("NodeType: {0}", node.NodeType.ToString().PadRight(10))); + switch (node.NodeType) + { + case XmlNodeType.Text: + sb.Append((node as XText).Value); + break; + case XmlNodeType.Element: + sb.Append((node as XElement).Name); + break; + case XmlNodeType.Comment: + sb.Append((node as XComment).Value); + break; + } + Console.WriteLine(sb.ToString()); +} +while ((node = node.PreviousNode) != null); +``` + +```vb +Dim xmlTree As XElement = _ + + 1Some Text2 + GrandChild Content + + + 3 + + +Dim node As XNode = xmlTree.Element("Child2") +Do + Dim sb As StringBuilder = New StringBuilder() + sb.Append(String.Format("NodeType: {0}", node.NodeType.ToString().PadRight(10))) + Select Case node.NodeType + Case XmlNodeType.Text + sb.Append(DirectCast(node, XText).Value) + Case XmlNodeType.Element + sb.Append(DirectCast(node, XElement).Name) + Case XmlNodeType.Comment + sb.Append(DirectCast(node, XComment).Value) + End Select + Console.WriteLine(sb.ToString()) + + node = node.PreviousNode +Loop While (Not (node Is Nothing)) +``` + + This example produces the following output: + +``` +NodeType: Element Child2 +NodeType: Text Some Text +NodeType: Element Child1 +``` + ]]> LINQ to XML overview @@ -2723,19 +2723,19 @@ NodeType: Element Child1 Creates an from an . An that contains the node and its descendant nodes that were read from the reader. The runtime type of the node is determined by the node type () of the first node encountered in the reader. - does not catch all exceptions thrown by the reader; the unhandled exceptions bubble up to the code that called . In particular, your code should be prepared to handle . - - For an example of how to stream a more complex document, see [How to stream XML fragments with access to header information](/dotnet/standard/linq/stream-xml-fragments-access-header-information). - - Certain standard query operators, such as , iterate their source, collect all of the data, sort it, and then finally yield the first item in the sequence. If you use a query operator that materializes its source before yielding the first item, you will not retain a small memory footprint. - - For an example of using LINQ to XML to transform extremely large XML documents while maintaining a small memory footprint, see [How to perform streaming transform of large XML documents](/dotnet/standard/linq/perform-streaming-transform-large-xml-documents). - + does not catch all exceptions thrown by the reader; the unhandled exceptions bubble up to the code that called . In particular, your code should be prepared to handle . + + For an example of how to stream a more complex document, see [How to stream XML fragments with access to header information](/dotnet/standard/linq/stream-xml-fragments-access-header-information). + + Certain standard query operators, such as , iterate their source, collect all of the data, sort it, and then finally yield the first item in the sequence. If you use a query operator that materializes its source before yielding the first item, you will not retain a small memory footprint. + + For an example of using LINQ to XML to transform extremely large XML documents while maintaining a small memory footprint, see [How to perform streaming transform of large XML documents](/dotnet/standard/linq/perform-streaming-transform-large-xml-documents). + ## Examples This example uses the following XML file, named *Source.xml*: @@ -2749,11 +2749,11 @@ The following example creates a custom axis method that uses The is not positioned on a recognized node type. @@ -2799,6 +2799,7 @@ ccc An XNode that contains the nodes read from the reader. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . The is not positioned on a recognized node type. + The cancellation token was canceled. This exception is stored into the returned task. @@ -2838,59 +2839,59 @@ ccc Removes this node from its parent. - by using the extension method. Then, you can iterate over the list to remove the nodes. For more information, see [Mixed Declarative Code/Imperative Code Bugs (LINQ to XML)](/dotnet/standard/linq/mixed-declarative-imperative-code-bugs). - - Alternatively, if you want to remove a set of nodes, it is recommended that you use the method. This method copies the nodes to a list, and then iterates over the list to remove the nodes. - - This method will raise the and the events. - + by using the extension method. Then, you can iterate over the list to remove the nodes. For more information, see [Mixed Declarative Code/Imperative Code Bugs (LINQ to XML)](/dotnet/standard/linq/mixed-declarative-imperative-code-bugs). + + Alternatively, if you want to remove a set of nodes, it is recommended that you use the method. This method copies the nodes to a list, and then iterates over the list to remove the nodes. + + This method will raise the and the events. + The stores its child nodes as a singly-linked list of objects. This means that the method must traverse the list of direct child nodes under the parent container. Therefore, using this method might affect your performance. - -## Examples - The following example removes a node from its parent. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", "child1 content"), - new XElement("Child2", "child2 content"), - new XElement("Child3", "child3 content"), - new XElement("Child4", "child4 content"), - new XElement("Child5", "child5 content") -); -XElement child3 = xmlTree.Element("Child3"); -child3.Remove(); -Console.WriteLine(xmlTree); -``` - -```vb -Dim xmlTree As XElement = _ - - child1 content - child2 content - child3 content - child4 content - child5 content - - -Dim child3 As XElement = xmlTree.(0) -child3.Remove() -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - child1 content - child2 content - child4 content - child5 content - -``` - + +## Examples + The following example removes a node from its parent. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XElement("Child3", "child3 content"), + new XElement("Child4", "child4 content"), + new XElement("Child5", "child5 content") +); +XElement child3 = xmlTree.Element("Child3"); +child3.Remove(); +Console.WriteLine(xmlTree); +``` + +```vb +Dim xmlTree As XElement = _ + + child1 content + child2 content + child3 content + child4 content + child5 content + + +Dim child3 As XElement = xmlTree.(0) +child3.Remove() +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + child1 content + child2 content + child4 content + child5 content + +``` + ]]> The parent is . @@ -2906,60 +2907,60 @@ Console.WriteLine(xmlTree) Replaces this node with the specified content. - and the events. - + and the events. + The stores its child nodes as a singly-linked list of objects. This means that the method must traverse the list of direct child nodes under the parent container. Therefore, using this method might affect your performance. - -## Examples - The following example uses this method to replace the contents of a node with different content. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", "child1 content"), - new XElement("Child2", "child2 content"), - new XElement("Child3", "child3 content"), - new XElement("Child4", "child4 content"), - new XElement("Child5", "child5 content") -); -XElement child3 = xmlTree.Element("Child3"); -child3.ReplaceWith( - new XElement("NewChild", "new content") -); -Console.WriteLine(xmlTree); -``` - -```vb -Dim xmlTree As XElement = _ - - child1 content - child2 content - child3 content - child4 content - child5 content - - -Dim child3 As XElement = xmlTree.(0) -child3.ReplaceWith(new content) -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - child1 content - child2 content - new content - child4 content - child5 content - -``` - + +## Examples + The following example uses this method to replace the contents of a node with different content. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XElement("Child3", "child3 content"), + new XElement("Child4", "child4 content"), + new XElement("Child5", "child5 content") +); +XElement child3 = xmlTree.Element("Child3"); +child3.ReplaceWith( + new XElement("NewChild", "new content") +); +Console.WriteLine(xmlTree); +``` + +```vb +Dim xmlTree As XElement = _ + + child1 content + child2 content + child3 content + child4 content + child5 content + + +Dim child3 As XElement = xmlTree.(0) +child3.ReplaceWith(new content) +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + child1 content + child2 content + new content + child4 content + child5 content + +``` + ]]> LINQ to XML overview @@ -3006,62 +3007,62 @@ Console.WriteLine(xmlTree) Content that replaces this node. Replaces this node with the specified content. - stores its child nodes as a singly-linked list of objects. This means that the method must traverse the list of direct child nodes under the parent container. Therefore, using this method might affect your performance. - - For details about the valid content that can be passed to this method, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - + stores its child nodes as a singly-linked list of objects. This means that the method must traverse the list of direct child nodes under the parent container. Therefore, using this method might affect your performance. + + For details about the valid content that can be passed to this method, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + This method will raise the and the events. - -## Examples - The following example uses this method to replace the contents of a node with different content. - -```csharp -XElement xmlTree = new XElement("Root", - new XElement("Child1", "child1 content"), - new XElement("Child2", "child2 content"), - new XElement("Child3", "child3 content"), - new XElement("Child4", "child4 content"), - new XElement("Child5", "child5 content") -); -XElement child3 = xmlTree.Element("Child3"); -child3.ReplaceWith( - new XElement("NewChild", "new content") -); -Console.WriteLine(xmlTree); -``` - -```vb -Dim xmlTree As XElement = _ - - child1 content - child2 content - child3 content - child4 content - child5 content - - -Dim child3 As XElement = xmlTree.(0) -child3.ReplaceWith(new content) -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - child1 content - child2 content - new content - child4 content - child5 content - -``` - + +## Examples + The following example uses this method to replace the contents of a node with different content. + +```csharp +XElement xmlTree = new XElement("Root", + new XElement("Child1", "child1 content"), + new XElement("Child2", "child2 content"), + new XElement("Child3", "child3 content"), + new XElement("Child4", "child4 content"), + new XElement("Child5", "child5 content") +); +XElement child3 = xmlTree.Element("Child3"); +child3.ReplaceWith( + new XElement("NewChild", "new content") +); +Console.WriteLine(xmlTree); +``` + +```vb +Dim xmlTree As XElement = _ + + child1 content + child2 content + child3 content + child4 content + child5 content + + +Dim child3 As XElement = xmlTree.(0) +child3.ReplaceWith(new content) +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + child1 content + child2 content + new content + child4 content + child5 content + +``` + ]]> LINQ to XML overview @@ -3121,85 +3122,85 @@ Console.WriteLine(xmlTree) A parameter list of the new content. Replaces this node with the specified content. - stores its child nodes as a singly-linked list of objects. This means that the method must traverse the list of direct child nodes under the parent container. Therefore, using this method might affect your performance. - - For details about the valid content that can be passed to this method, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). - + stores its child nodes as a singly-linked list of objects. This means that the method must traverse the list of direct child nodes under the parent container. Therefore, using this method might affect your performance. + + For details about the valid content that can be passed to this method, see [Valid Content of XElement and XDocument Objects](/dotnet/standard/linq/valid-content-xelement-xdocument-objects). + This method will raise the and the events. - -## Examples - The following example shows using the results of a LINQ to XML query as the input to this method. - -```csharp -XElement srcTree = new XElement("Root", - new XElement("Element1", 1), - new XElement("Element2", 2), - new XElement("Element3", 3), - new XElement("Element4", 4), - new XElement("Element5", 5) -); -XElement xmlTree = new XElement("Root", - new XElement("Child1", 1), - new XElement("Child2", 2), - new XElement("Child3", 3), - new XElement("Child4", 4), - new XElement("Child5", 5) -); -XElement child3 = xmlTree.Element("Child3"); -child3.ReplaceWith( - from el in srcTree.Elements() - where (int)el > 3 - select el -); -Console.WriteLine(xmlTree); -``` - -```vb -Dim srcTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim xmlTree As XElement = _ - - 1 - 2 - 3 - 4 - 5 - - -Dim child3 As XElement = xmlTree.(0) -child3.ReplaceWith( _ - From el In srcTree.Elements() _ - Where (CInt(el) > 3) _ - Select el) - -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - 1 - 2 - 4 - 5 - 4 - 5 - -``` - + +## Examples + The following example shows using the results of a LINQ to XML query as the input to this method. + +```csharp +XElement srcTree = new XElement("Root", + new XElement("Element1", 1), + new XElement("Element2", 2), + new XElement("Element3", 3), + new XElement("Element4", 4), + new XElement("Element5", 5) +); +XElement xmlTree = new XElement("Root", + new XElement("Child1", 1), + new XElement("Child2", 2), + new XElement("Child3", 3), + new XElement("Child4", 4), + new XElement("Child5", 5) +); +XElement child3 = xmlTree.Element("Child3"); +child3.ReplaceWith( + from el in srcTree.Elements() + where (int)el > 3 + select el +); +Console.WriteLine(xmlTree); +``` + +```vb +Dim srcTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim xmlTree As XElement = _ + + 1 + 2 + 3 + 4 + 5 + + +Dim child3 As XElement = xmlTree.(0) +child3.ReplaceWith( _ + From el In srcTree.Elements() _ + Where (CInt(el) > 3) _ + Select el) + +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + 1 + 2 + 4 + 5 + 4 + 5 + +``` + ]]> LINQ to XML overview @@ -3255,35 +3256,35 @@ Console.WriteLine(xmlTree) Returns the indented XML for this node. A containing the indented XML. - - 1 - - -Console.WriteLine(xmlTree) -``` - - This example produces the following output: - -```xml - - 1 - -``` - + + 1 + + +Console.WriteLine(xmlTree) +``` + + This example produces the following output: + +```xml + + 1 + +``` + ]]> LINQ to XML overview @@ -3336,37 +3337,37 @@ Console.WriteLine(xmlTree) Returns the XML for this node, optionally disabling formatting. A containing the XML. - "); -Console.WriteLine(root.ToString(SaveOptions.DisableFormatting)); -Console.WriteLine("---"); -Console.WriteLine(root.ToString(SaveOptions.None)); -``` - -```vb -Dim root As XElement = - - -Console.WriteLine(root.ToString(SaveOptions.DisableFormatting)) -Console.WriteLine("---") -Console.WriteLine(root.ToString(SaveOptions.None)) -``` - - This example produces the following output: - -``` - ---- - - - -``` - + "); +Console.WriteLine(root.ToString(SaveOptions.DisableFormatting)); +Console.WriteLine("---"); +Console.WriteLine(root.ToString(SaveOptions.None)); +``` + +```vb +Dim root As XElement = + + +Console.WriteLine(root.ToString(SaveOptions.DisableFormatting)) +Console.WriteLine("---") +Console.WriteLine(root.ToString(SaveOptions.None)) +``` + + This example produces the following output: + +``` + +--- + + + +``` + ]]> LINQ to XML overview @@ -3412,70 +3413,70 @@ Console.WriteLine(root.ToString(SaveOptions.None)) An into which this method will write. Writes this node to an . - that writes to a . It then uses this method to write two XML trees to the writer. - -```csharp -StringBuilder sb = new StringBuilder(); -XmlWriterSettings xws = new XmlWriterSettings(); -xws.OmitXmlDeclaration = true; -xws.Indent = true; - -using (XmlWriter xw = XmlWriter.Create(sb, xws)) { - xw.WriteStartElement("Root"); - XElement child1 = new XElement("Child", - new XElement("GrandChild", "some content") - ); - child1.WriteTo(xw); - XElement child2 = new XElement("AnotherChild", - new XElement("GrandChild", "different content") - ); - child2.WriteTo(xw); - xw.WriteEndElement(); -} -Console.WriteLine(sb.ToString()); -``` - -```vb -Dim sb As StringBuilder = New StringBuilder() -Dim xws As XmlWriterSettings = New XmlWriterSettings() -xws.OmitXmlDeclaration = True -xws.Indent = True - -Using xw = XmlWriter.Create(sb, xws) - xw.WriteStartElement("Root") - Dim child1 As XElement = - some content - - child1.WriteTo(xw) - Dim child2 As XElement = - different content - - child2.WriteTo(xw) - xw.WriteEndElement() -End Using - -Console.WriteLine(sb.ToString()) -``` - - This example produces the following output: - -```xml - - - some content - - - different content - - -``` - + +## Examples + The following example creates an that writes to a . It then uses this method to write two XML trees to the writer. + +```csharp +StringBuilder sb = new StringBuilder(); +XmlWriterSettings xws = new XmlWriterSettings(); +xws.OmitXmlDeclaration = true; +xws.Indent = true; + +using (XmlWriter xw = XmlWriter.Create(sb, xws)) { + xw.WriteStartElement("Root"); + XElement child1 = new XElement("Child", + new XElement("GrandChild", "some content") + ); + child1.WriteTo(xw); + XElement child2 = new XElement("AnotherChild", + new XElement("GrandChild", "different content") + ); + child2.WriteTo(xw); + xw.WriteEndElement(); +} +Console.WriteLine(sb.ToString()); +``` + +```vb +Dim sb As StringBuilder = New StringBuilder() +Dim xws As XmlWriterSettings = New XmlWriterSettings() +xws.OmitXmlDeclaration = True +xws.Indent = True + +Using xw = XmlWriter.Create(sb, xws) + xw.WriteStartElement("Root") + Dim child1 As XElement = + some content + + child1.WriteTo(xw) + Dim child2 As XElement = + different content + + child2.WriteTo(xw) + xw.WriteEndElement() +End Using + +Console.WriteLine(sb.ToString()) +``` + + This example produces the following output: + +```xml + + + some content + + + different content + + +``` + ]]> LINQ to XML overview @@ -3518,6 +3519,7 @@ Console.WriteLine(sb.ToString()) Writes the current node to an . A task representing the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Xml.Linq/XProcessingInstruction.xml b/xml/System.Xml.Linq/XProcessingInstruction.xml index e26502050e8..f06333ba130 100644 --- a/xml/System.Xml.Linq/XProcessingInstruction.xml +++ b/xml/System.Xml.Linq/XProcessingInstruction.xml @@ -40,13 +40,13 @@ Represents an XML processing instruction. - node. - + node. + ]]> LINQ to XML overview @@ -101,11 +101,11 @@ The node to copy from. Initializes a new instance of the class. - LINQ to XML overview @@ -150,27 +150,27 @@ The string data for this . Initializes a new instance of the class. - , and specifies a target and the string data for the processing instruction. - -```csharp -XProcessingInstruction pi = new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='hello.xsl'"); -Console.WriteLine(pi); -``` - -```vb -Dim pi As XProcessingInstruction = -Console.WriteLine(pi) -``` - - This example produces the following output: - -``` - -``` - + , and specifies a target and the string data for the processing instruction. + +```csharp +XProcessingInstruction pi = new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='hello.xsl'"); +Console.WriteLine(pi); +``` + +```vb +Dim pi As XProcessingInstruction = +Console.WriteLine(pi) +``` + + This example produces the following output: + +``` + +``` + ]]> The or parameter is . @@ -221,38 +221,38 @@ Console.WriteLine(pi) Gets or sets the string value of this processing instruction. A that contains the string value of this processing instruction. - property to retrieve the string value of a processing instruction. - -```csharp -XProcessingInstruction pi = - new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='hello.xsl'"); -Console.WriteLine(pi.Data); -pi.Data = "type='text/xsl' href='xform.xsl'"; -Console.WriteLine(pi.Data); -``` - -```vb -Dim pi As XProcessingInstruction = -Console.WriteLine(pi.Data) -pi.Data = "type='text/xsl' href='xform.xsl'" -Console.WriteLine(pi.Data) -``` - - This example produces the following output: - -``` -type='text/xsl' href='hello.xsl' -type='text/xsl' href='xform.xsl' -``` - + property to retrieve the string value of a processing instruction. + +```csharp +XProcessingInstruction pi = + new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='hello.xsl'"); +Console.WriteLine(pi.Data); +pi.Data = "type='text/xsl' href='xform.xsl'"; +Console.WriteLine(pi.Data); +``` + +```vb +Dim pi As XProcessingInstruction = +Console.WriteLine(pi.Data) +pi.Data = "type='text/xsl' href='xform.xsl'" +Console.WriteLine(pi.Data) +``` + + This example produces the following output: + +``` +type='text/xsl' href='hello.xsl' +type='text/xsl' href='xform.xsl' +``` + ]]> The string is . @@ -296,34 +296,34 @@ type='text/xsl' href='xform.xsl' Gets the node type for this node. The node type. For objects, this value is . - contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. - - - -## Examples - The following example creates a processing instruction, and then prints its node type. - -```csharp -XProcessingInstruction pi = - new XProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"hello.xsl\""); -Console.WriteLine(pi.NodeType); -``` - -```vb -Dim pi As XProcessingInstruction = _ - -Console.WriteLine(pi.NodeType.ToString) -``` - - This example produces the following output: - -``` -ProcessingInstruction -``` - + contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. + + + +## Examples + The following example creates a processing instruction, and then prints its node type. + +```csharp +XProcessingInstruction pi = + new XProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"hello.xsl\""); +Console.WriteLine(pi.NodeType); +``` + +```vb +Dim pi As XProcessingInstruction = _ + +Console.WriteLine(pi.NodeType.ToString) +``` + + This example produces the following output: + +``` +ProcessingInstruction +``` + ]]> LINQ to XML overview @@ -372,29 +372,29 @@ ProcessingInstruction Gets or sets a string containing the target application for this processing instruction. A containing the target application for this processing instruction. - property to retrieve the target application for a processing instruction. - -```csharp -XProcessingInstruction pi = - new XProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"hello.xsl\""); -Console.WriteLine(pi.Target); -``` - -```vb -Dim pi As XProcessingInstruction = _ - -Console.WriteLine(pi.Target) -``` - - This example produces the following output: - -``` -xml-stylesheet -``` - + property to retrieve the target application for a processing instruction. + +```csharp +XProcessingInstruction pi = + new XProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"hello.xsl\""); +Console.WriteLine(pi.Target); +``` + +```vb +Dim pi As XProcessingInstruction = _ + +Console.WriteLine(pi.Target) +``` + + This example produces the following output: + +``` +xml-stylesheet +``` + ]]> The string is . @@ -442,11 +442,11 @@ xml-stylesheet The to write this processing instruction to. Writes this processing instruction to an . - . - + . + ]]> LINQ to XML overview @@ -489,6 +489,7 @@ xml-stylesheet Writes this to the specified . A task representing the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System.Xml.Linq/XText.xml b/xml/System.Xml.Linq/XText.xml index 1e23a006a70..a340158e816 100644 --- a/xml/System.Xml.Linq/XText.xml +++ b/xml/System.Xml.Linq/XText.xml @@ -40,17 +40,17 @@ Represents a text node. - node. - - LINQ to XML developers will often have to write code to work with arbitrary LINQ to XML trees that they did not create. If you are writing code that has to work with LINQ to XML trees that you have no control over creating, you should be aware of certain behaviors of nodes. - - When processing the contents of an XML tree at the node level, you should be prepared for multiple nodes to be adjacent to each other. Further, you should be prepared for nodes that contain no text. It is possible through LINQ to XML methods to remove the content of a text node. However, LINQ to XML does not automatically delete the node. The node has identity, and might have annotations, so LINQ to XML allows for zero-length nodes in the tree. - - For more information, see [Programming with nodes](/dotnet/standard/linq/program-nodes). - + node. + + LINQ to XML developers will often have to write code to work with arbitrary LINQ to XML trees that they did not create. If you are writing code that has to work with LINQ to XML trees that you have no control over creating, you should be aware of certain behaviors of nodes. + + When processing the contents of an XML tree at the node level, you should be prepared for multiple nodes to be adjacent to each other. Further, you should be prepared for nodes that contain no text. It is possible through LINQ to XML methods to remove the content of a text node. However, LINQ to XML does not automatically delete the node. The node has identity, and might have annotations, so LINQ to XML allows for zero-length nodes in the tree. + + For more information, see [Programming with nodes](/dotnet/standard/linq/program-nodes). + ]]> LINQ to XML overview @@ -105,32 +105,32 @@ The that contains the value of the node. Initializes a new instance of the class. - constructors. When you pass text content when constructing an , text nodes are automatically created. - - - -## Examples - The following example creates an element that contains a text node. - -```csharp -XElement root = new XElement("Root", "Some text"); -Console.WriteLine(root); -``` - -```vb -Dim root As XElement = Some text -Console.WriteLine(root) -``` - - This example produces the following output: - -```xml -Some text -``` - + constructors. When you pass text content when constructing an , text nodes are automatically created. + + + +## Examples + The following example creates an element that contains a text node. + +```csharp +XElement root = new XElement("Root", "Some text"); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement = Some text +Console.WriteLine(root) +``` + + This example produces the following output: + +```xml +Some text +``` + ]]> LINQ to XML overview @@ -173,11 +173,11 @@ Console.WriteLine(root) The node to copy from. Initializes a new instance of the class from another object. - LINQ to XML overview @@ -220,79 +220,79 @@ Console.WriteLine(root) Gets the node type for this node. The node type. For objects, this value is . - contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. - - - -## Examples - The following example creates an XML tree that contains a number of types of nodes. It then iterates through the tree, outputting the node type of each node. - - Note that `Child2` contains an node, implicitly converted from the string content. - -```csharp -// Note that XNode uses XmlNodeType, which is in the System.Xml namespace. -XDocument xmlTree = new XDocument( - new XComment("a comment"), - new XProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"hello.xsl\""), - new XElement("Root", - new XAttribute("Att", "attContent"), - new XElement("Child1", - new XCData("CDATA content") - ), - new XElement("Child2", "Text content") - ) -); - -foreach (XNode node in xmlTree.DescendantNodes()) -{ - Console.WriteLine(node.NodeType); - if (node.NodeType == XmlNodeType.Element) - { - foreach (XAttribute att in ((XElement)node).Attributes()) - Console.WriteLine(att.NodeType); - } -} -``` - -```vb -' Note that XNode uses XmlNodeType, which is in the System.Xml namespace. -Dim xmlTree As XDocument = _ - - - - - - - - Text content - - -For Each node As XNode In xmlTree.DescendantNodes - Console.WriteLine(node.NodeType.ToString()) - If node.NodeType = XmlNodeType.Element Then - For Each att In DirectCast(node, XElement).Attributes - Console.WriteLine(att.NodeType.ToString()) - Next - End If -Next -``` - - This example produces the following output: - -``` -Comment -ProcessingInstruction -Element -Attribute -Element -CDATA -Element -Text -``` - + contain a property, you can write code that operates on collections of concrete subclass of . Your code can then test for the node type of each node in the collection. + + + +## Examples + The following example creates an XML tree that contains a number of types of nodes. It then iterates through the tree, outputting the node type of each node. + + Note that `Child2` contains an node, implicitly converted from the string content. + +```csharp +// Note that XNode uses XmlNodeType, which is in the System.Xml namespace. +XDocument xmlTree = new XDocument( + new XComment("a comment"), + new XProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"hello.xsl\""), + new XElement("Root", + new XAttribute("Att", "attContent"), + new XElement("Child1", + new XCData("CDATA content") + ), + new XElement("Child2", "Text content") + ) +); + +foreach (XNode node in xmlTree.DescendantNodes()) +{ + Console.WriteLine(node.NodeType); + if (node.NodeType == XmlNodeType.Element) + { + foreach (XAttribute att in ((XElement)node).Attributes()) + Console.WriteLine(att.NodeType); + } +} +``` + +```vb +' Note that XNode uses XmlNodeType, which is in the System.Xml namespace. +Dim xmlTree As XDocument = _ + + + + + + + + Text content + + +For Each node As XNode In xmlTree.DescendantNodes + Console.WriteLine(node.NodeType.ToString()) + If node.NodeType = XmlNodeType.Element Then + For Each att In DirectCast(node, XElement).Attributes + Console.WriteLine(att.NodeType.ToString()) + Next + End If +Next +``` + + This example produces the following output: + +``` +Comment +ProcessingInstruction +Element +Attribute +Element +CDATA +Element +Text +``` + ]]> LINQ to XML overview @@ -341,48 +341,48 @@ Text Gets or sets the value of this node. A that contains the value of this node. - and the events. - - - -## Examples - The following example shows getting and setting this property. - -```csharp -XElement root = new XElement("Root", "Some text"); -XText txtNode = root.Nodes().OfType().First(); -Console.WriteLine(txtNode.Value); -txtNode.Value = "New text"; -Console.WriteLine(txtNode.Value); - -root.Value = "Newer text"; -txtNode = root.Nodes().OfType().First(); -Console.WriteLine(txtNode.Value); -``` - -```vb -Dim root As XElement = Some text -Dim txtNode As XText = root.Nodes().OfType(Of XText).First() -Console.WriteLine(txtNode.Value) -txtNode.Value = "New text" -Console.WriteLine(txtNode.Value) - -root.Value = "Newer text" -txtNode = root.Nodes().OfType(Of XText).First() -Console.WriteLine(txtNode.Value) -``` - - This example produces the following output: - -``` -Some text -New text -Newer text -``` - + and the events. + + + +## Examples + The following example shows getting and setting this property. + +```csharp +XElement root = new XElement("Root", "Some text"); +XText txtNode = root.Nodes().OfType().First(); +Console.WriteLine(txtNode.Value); +txtNode.Value = "New text"; +Console.WriteLine(txtNode.Value); + +root.Value = "Newer text"; +txtNode = root.Nodes().OfType().First(); +Console.WriteLine(txtNode.Value); +``` + +```vb +Dim root As XElement = Some text +Dim txtNode As XText = root.Nodes().OfType(Of XText).First() +Console.WriteLine(txtNode.Value) +txtNode.Value = "New text" +Console.WriteLine(txtNode.Value) + +root.Value = "Newer text" +txtNode = root.Nodes().OfType(Of XText).First() +Console.WriteLine(txtNode.Value) +``` + + This example produces the following output: + +``` +Some text +New text +Newer text +``` + ]]> LINQ to XML overview @@ -428,11 +428,11 @@ Newer text An into which this method will write. Writes this node to an . - . - + . + ]]> LINQ to XML overview @@ -475,6 +475,7 @@ Newer text Asynchronously writes this to the specified . A task representing the asynchronous write operation. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System/BinaryData.xml b/xml/System/BinaryData.xml index 9b2e7b46e83..f7779956fcb 100644 --- a/xml/System/BinaryData.xml +++ b/xml/System/BinaryData.xml @@ -390,6 +390,7 @@ Creates a instance from the specified stream. The stream is not disposed by this method. A value representing all of the data remaining in . This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + The cancellation token was canceled. This exception is stored into the returned task. diff --git a/xml/System/OperationCanceledException.xml b/xml/System/OperationCanceledException.xml index e721db7691e..bf8c08862f9 100644 --- a/xml/System/OperationCanceledException.xml +++ b/xml/System/OperationCanceledException.xml @@ -63,11 +63,11 @@ The exception that is thrown in a thread upon cancellation of an operation that the thread was executing. - property, and the property of the token is set to `true`. - + property, and the property of the token is set to `true`. + ]]> @@ -121,19 +121,19 @@ Initializes a new instance of the class with a system-supplied error message. - property of the new instance to a system-supplied message that describes the error, such as "The operation was canceled." This message takes into account the current system culture. - - The following table shows the initial property values for an instance of . - -|Property|Value| -|--------------|-----------| -||A nullreference (`Nothing` in Visual Basic).| -||The localized error message string.| -||A cancellation token created in the non-canceled state.| - + property of the new instance to a system-supplied message that describes the error, such as "The operation was canceled." This message takes into account the current system culture. + + The following table shows the initial property values for an instance of . + +|Property|Value| +|--------------|-----------| +||A nullreference (`Nothing` in Visual Basic).| +||The localized error message string.| +||A cancellation token created in the non-canceled state.| + ]]> @@ -181,19 +181,19 @@ A that describes the error. Initializes a new instance of the class with a specified error message. - . - -|Property|Value| -|--------------|-----------| -||A null reference (`Nothing` in Visual Basic).| -||The error message string.| -||A cancellation token created in the non-canceled state.| - + . + +|Property|Value| +|--------------|-----------| +||A null reference (`Nothing` in Visual Basic).| +||The error message string.| +||A cancellation token created in the non-canceled state.| + ]]> @@ -239,23 +239,24 @@ A cancellation token associated with the operation that was canceled. Initializes a new instance of the class with a cancellation token. - property of the new instance to a system-supplied message that describes the error, such as "The operation was canceled." This message takes into account the current system culture. - - The following table shows the initial property values for an instance of . - -|Property|Value| -|--------------|-----------| -||A nullreference (`Nothing` in Visual Basic).| -||The localized error message string.| -||`token`.| - + property of the new instance to a system-supplied message that describes the error, such as "The operation was canceled." This message takes into account the current system culture. + + The following table shows the initial property values for an instance of . + +|Property|Value| +|--------------|-----------| +||A nullreference (`Nothing` in Visual Basic).| +||The localized error message string.| +||`token`.| + ]]> Handling and Throwing Exceptions + The cancellation token was canceled. This exception is stored into the returned task. @@ -298,11 +299,11 @@ The contextual information about the source or destination. Initializes a new instance of the class with serialized data. - XML and SOAP Serialization @@ -351,21 +352,21 @@ The exception that is the cause of the current exception. If the parameter is not , the current exception is raised in a block that handles the inner exception. Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - property. The property returns the same value that is passed into the constructor, or `null` if the property does not supply the inner exception value to the constructor. - - The following table shows the initial property values for an instance of . - -|Property Type|Condition| -|-------------------|---------------| -||`innerException`.| -||`message`.| -||A cancellation token created in the non-canceled state.| - + property. The property returns the same value that is passed into the constructor, or `null` if the property does not supply the inner exception value to the constructor. + + The following table shows the initial property values for an instance of . + +|Property Type|Condition| +|-------------------|---------------| +||`innerException`.| +||`message`.| +||A cancellation token created in the non-canceled state.| + ]]> @@ -414,23 +415,24 @@ A cancellation token associated with the operation that was canceled. Initializes a new instance of the class with a specified error message and a cancellation token. - . - -|Property|Value| -|--------------|-----------| -||A null reference (`Nothing` in Visual Basic).| -||`message`.| -||`token`.| - + . + +|Property|Value| +|--------------|-----------| +||A null reference (`Nothing` in Visual Basic).| +||`message`.| +||`token`.| + ]]> Handling and Throwing Exceptions + The cancellation token was canceled. This exception is stored into the returned task. @@ -477,25 +479,26 @@ A cancellation token associated with the operation that was canceled. Initializes a new instance of the class with a specified error message, a reference to the inner exception that is the cause of this exception, and a cancellation token. - property. The property returns the same value that is passed into the constructor, or `null` if the property does not supply the inner exception value to the constructor. - - The following table shows the initial property values for an instance of . - -|Property Type|Condition| -|-------------------|---------------| -||`innerException`.| -||`message`.| -||`token`.| - + property. The property returns the same value that is passed into the constructor, or `null` if the property does not supply the inner exception value to the constructor. + + The following table shows the initial property values for an instance of . + +|Property Type|Condition| +|-------------------|---------------| +||`innerException`.| +||`message`.| +||`token`.| + ]]> Handling and Throwing Exceptions + The cancellation token was canceled. This exception is stored into the returned task. @@ -537,11 +540,11 @@ Gets a token associated with the operation that was canceled. A token associated with the operation that was canceled, or a default token. - property of the token returns `true`. - + property of the token returns `true`. + ]]> diff --git a/xml/System/WindowsRuntimeSystemExtensions.xml b/xml/System/WindowsRuntimeSystemExtensions.xml index 1358c97af85..d28b20fe981 100644 --- a/xml/System/WindowsRuntimeSystemExtensions.xml +++ b/xml/System/WindowsRuntimeSystemExtensions.xml @@ -76,7 +76,7 @@ The methods are used Use this method when you want to pass a task to a Windows Runtime method that takes an asynchronous action. -The class provides static methods (`Shared` methods in Visual Basic) that create and start Windows Runtime asynchronous actions that represent tasks that can respond to cancellation requests and report progress. +The class provides static methods (`Shared` methods in Visual Basic) that create and start Windows Runtime asynchronous actions that represent tasks that can respond to cancellation requests and report progress. ]]> @@ -213,6 +213,7 @@ Use this method to get a object for a Windows is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -351,6 +352,7 @@ Calling this method overload is equivalent to calling the is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -398,6 +400,7 @@ Use this method to get a object for a Windows is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -486,6 +489,7 @@ Use this method to get a object for a Win is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -526,7 +530,7 @@ Use this method to get a object for a Win > [!NOTE] > In Visual Basic and C#, you can call this method as an instance method on any object of type . When you use instance method syntax to call this method, omit the first parameter. For more information, see [Extension Methods (Visual Basic)](/dotnet/visual-basic/programming-guide/language-features/procedures/extension-methods) or [Extension Methods (C# Programming Guide)](/dotnet/csharp/programming-guide/classes-and-structs/extension-methods). -Use this method to get a object for a Windows Runtime asynchronous operation. objects simplify the coordination of asynchronous operations. +Use this method to get a object for a Windows Runtime asynchronous operation. objects simplify the coordination of asynchronous operations. Calling this method overload is equivalent to calling the extension method overload and specifying `null` for the `progress` parameter. This is useful when you don't want to get progress reports from an action that reports progress. @@ -632,6 +636,7 @@ Calling this method overload is equivalent to calling the is . + The cancellation token was canceled. This exception is stored into the returned task. @@ -680,6 +685,7 @@ Use this method to get a object for a Win ]]> + The cancellation token was canceled. This exception is stored into the returned task.