From ed1417a89b75a0cc7d18285220a0de7062429c85 Mon Sep 17 00:00:00 2001 From: olprod Date: Fri, 12 Oct 2018 08:59:39 +0000 Subject: [PATCH] commit translated contents --- docs/core/index.md | 12 +- docs/core/migration/20-21.md | 8 +- docs/core/packages.md | 24 +- docs/core/porting/index.md | 24 +- docs/core/tools/csproj.md | 46 +- docs/core/tools/dotnet-clean.md | 26 +- docs/core/tools/dotnet-pack.md | 24 +- docs/core/tools/global-tools-how-to-create.md | 195 ++ docs/core/tools/using-ci-with-cli.md | 24 +- docs/core/tutorials/using-with-xplat-cli.md | 29 +- docs/core/versions/selection.md | 15 +- docs/csharp/event-pattern.md | 22 +- docs/csharp/getting-started/index.md | 8 +- .../formatting-numeric-results-table.md | 74 +- docs/csharp/language-reference/keywords/is.md | 18 +- .../keywords/reference-tables-for-types.md | 37 +- .../language-reference/keywords/try-catch.md | 8 +- .../operators/or-operator.md | 10 +- .../language-reference/tokens/verbatim.md | 49 +- ...cancel-an-async-task-or-a-list-of-tasks.md | 1030 ++++++----- ...ncel-async-tasks-after-a-period-of-time.md | 426 ++--- .../async/control-flow-in-async-programs.md | 758 ++++---- ...tasks-and-process-them-as-they-complete.md | 450 ++--- ...essing-the-web-by-using-async-and-await.md | 1414 +++++++------- .../concepts/caller-information.md | 152 +- ...-vs-functional-construction-linq-to-xml.md | 8 +- .../how-to-identify-a-nullable-type.md | 14 +- .../csharp/programming-guide/strings/index.md | 10 +- docs/csharp/quick-starts/hello-world.yml | 18 +- docs/csharp/roslyn-sdk/toc.md | 3 +- .../how-to-write-csharp-analyzer-code-fix.md | 527 ++++++ docs/csharp/tutorials/console-teleprompter.md | 20 +- docs/csharp/whats-new/csharp-6.md | 28 +- docs/csharp/whats-new/csharp-7-2.md | 26 +- docs/csharp/whats-new/csharp-7-3.md | 16 +- docs/csharp/whats-new/csharp-7.md | 32 +- .../version-update-considerations.md | 65 + .../create-and-use-strong-named-assemblies.md | 158 +- ...how-to-install-an-assembly-into-the-gac.md | 116 +- ...ow-to-reference-a-strong-named-assembly.md | 42 +- .../how-to-view-the-contents-of-the-gac.md | 49 +- .../marshaling-data-with-platform-invoke.md | 16 +- docs/framework/mef/index.md | 932 +++++----- .../migrating-from-the-net-framework-1-1.md | 112 +- .../net-framework-4-migration-issues.md | 41 +- .../introducing-pluggable-protocols.md | 11 +- .../making-asynchronous-requests.md | 41 +- docs/framework/network-programming/tls.md | 13 +- .../dynamic-language-runtime-overview.md | 167 +- .../tools/developer-command-prompt-for-vs.md | 20 +- ...xe-manifest-generation-and-editing-tool.md | 27 +- .../regasm-exe-assembly-registration-tool.md | 174 +- .../tools/sos-dll-sos-debugging-extension.md | 391 ++-- docs/framework/windows-services/index.md | 74 +- ...e-application-in-the-component-designer.md | 935 +++++----- docs/machine-learning/tutorials/index.md | 13 +- .../tutorials/sentiment-analysis.md | 8 +- ...ling-synchronous-methods-asynchronously.md | 141 +- ...ts-the-event-based-asynchronous-pattern.md | 10 +- ...ing-the-task-based-asynchronous-pattern.md | 1641 +++++++++-------- ...rt-the-event-based-asynchronous-pattern.md | 10 +- ...ng-the-event-based-asynchronous-pattern.md | 44 +- .../base-types/best-practices-strings.md | 21 +- docs/standard/base-types/comparing.md | 13 +- .../custom-numeric-format-strings.md | 89 +- .../implementing-dispose.md | 10 +- ...-culture-insensitive-string-comparisons.md | 10 +- ...g-culture-insensitive-string-operations.md | 11 +- docs/standard/io/asynchronous-file-i-o.md | 75 +- docs/standard/io/index.md | 10 +- docs/standard/io/toc.md | 1 + ...nication-versus-the-API-Gateway-pattern.md | 10 +- .../docker-containers-images-registries.md | 30 +- .../docker-defined.md | 85 +- .../docker-terminology.md | 40 +- .../container-docker-introduction/index.md | 28 +- .../microservices-architecture/index.md | 133 +- .../data-driven-crud-microservice.md | 10 +- ...i-container-applications-docker-compose.md | 12 +- .../container-framework-choice-factors.md | 130 +- .../general-guidance.md | 34 +- .../index.md | 24 +- .../net-container-os-targets.md | 74 +- .../net-core-container-scenarios.md | 34 +- .../net-framework-container-scenarios.md | 48 +- .../official-net-docker-images.md | 42 +- .../development-process-for-azure.md | 22 +- ...l-invoke-to-execute-parallel-operations.md | 46 +- ...how-to-write-a-simple-parallel-for-loop.md | 109 +- ...to-write-a-simple-parallel-foreach-loop.md | 72 +- docs/standard/parallel-programming/index.md | 20 +- .../task-based-asynchronous-programming.md | 49 +- docs/standard/threading/barrier.md | 49 +- ...etevent-countdownevent-manualresetevent.md | 50 +- docs/standard/threading/eventwaithandle.md | 10 +- ...-spinlock-for-low-level-synchronization.md | 20 +- .../threading/interlocked-operations.md | 37 +- docs/toc.md | 3 +- includes/csharp-interactive-partial-note.md | 3 + includes/dotnet-restore-note-options.md | 2 +- includes/dotnet-restore-note.md | 2 +- 101 files changed, 6636 insertions(+), 5668 deletions(-) create mode 100644 docs/core/tools/global-tools-how-to-create.md create mode 100644 docs/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix.md create mode 100644 docs/csharp/whats-new/version-update-considerations.md create mode 100644 includes/csharp-interactive-partial-note.md diff --git a/docs/core/index.md b/docs/core/index.md index ef6d338d082..2e9a4b1df25 100644 --- a/docs/core/index.md +++ b/docs/core/index.md @@ -5,12 +5,12 @@ author: richlander ms.author: mairaw ms.date: 08/01/2018 ms.custom: updateeachrelease -ms.openlocfilehash: cfa7c27871204b808c9d753a970d5abb907a183e -ms.sourcegitcommit: 2eceb05f1a5bb261291a1f6a91c5153727ac1c19 +ms.openlocfilehash: b302b6fc7e097a811c718d2244f603246cb5c259 +ms.sourcegitcommit: 15d99019aea4a5c3c91ddc9ba23692284a7f61f3 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/04/2018 -ms.locfileid: "43512842" +ms.lasthandoff: 10/12/2018 +ms.locfileid: "49121039" --- # .NET Core のガイド @@ -18,7 +18,7 @@ ms.locfileid: "43512842" 特徴、サポートされる言語とフレームワーク、キー API など、.NET Core について詳しくは、「[About .NET Core](about.md)」(.NET Core について) をご覧ください。 -「[.NET Core チュートリアル](tutorials/index.md)」では、単純な .NET Core アプリケーションを作成する方法を学習できます。 最初のアプリを、ほんの数分で起動および実行できます。 ブラウザーで .NET Core を使用してみたい場合は、[C# における数値](https://docs.microsoft.com/dotnet/csharp/quick-starts/hello-world)に関するクイックスタートをご覧ください。 +「[.NET Core チュートリアル](tutorials/index.md)」では、単純な .NET Core アプリケーションを作成する方法を学習できます。 最初のアプリを、ほんの数分で起動および実行できます。 ブラウザーで .NET Core を使用してみたい場合は、[C# における数値](https://docs.microsoft.com/dotnet/csharp/quick-starts/numbers-in-csharp)に関するクイックスタートをご覧ください。 ## NET Core 2.1 のダウンロード @@ -51,4 +51,4 @@ Hello World! .NET Core のバイナリ形式の配布は、Azure 内のマイクロソフトが管理するサーバーで構築されてテストされ、他のすべてのマイクロソフト製品と同様にサポートされます。 -Red Hat Enterprise Linux (RHEL) では [.NET Core は Red Hat によってサポート](http://redhatloves.net/)されます。 Red Hat がソースから .NET Core をビルドして、[Red Hat ソフトウェア コレクション](https://developers.redhat.com/products/softwarecollections/overview/)で使用できるようにします。 Red Hat とマイクロソフトが共同して、.NET Core が RHEL 上で適切に動作するようにします。 \ No newline at end of file +Red Hat Enterprise Linux (RHEL) では [.NET Core は Red Hat によってサポート](http://redhatloves.net/)されます。 Red Hat がソースから .NET Core をビルドして、[Red Hat ソフトウェア コレクション](https://developers.redhat.com/products/softwarecollections/overview/)で使用できるようにします。 Red Hat とマイクロソフトが共同して、.NET Core が RHEL 上で適切に動作するようにします。 diff --git a/docs/core/migration/20-21.md b/docs/core/migration/20-21.md index 06a4e0f75e9..e67c9121dd1 100644 --- a/docs/core/migration/20-21.md +++ b/docs/core/migration/20-21.md @@ -4,12 +4,12 @@ description: .NET Core 2.0 アプリを 2.1 にアップグレードする方法 author: mairaw ms.author: mairaw ms.date: 08/06/2018 -ms.openlocfilehash: 9695935fb50652d30996afbd669493e50d590e74 -ms.sourcegitcommit: 64f4baed249341e5bf64d1385bf48e3f2e1a0211 +ms.openlocfilehash: ace0ca403163ebb304e002107d992d7d6f1124bf +ms.sourcegitcommit: 5bbfe34a9a14e4ccb22367e57b57585c208cf757 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/07/2018 -ms.locfileid: "44087964" +ms.lasthandoff: 09/18/2018 +ms.locfileid: "45989590" --- # .NET Core 2.0 から 2.1 への移行 diff --git a/docs/core/packages.md b/docs/core/packages.md index c4b5fc9cb96..ce2e184e77e 100644 --- a/docs/core/packages.md +++ b/docs/core/packages.md @@ -1,15 +1,15 @@ --- -title: パッケージ、メタパッケージ、フレームワーク -description: パッケージ、メタパッケージ、フレームワークの用語を説明します。 -author: richlander -ms.author: mairaw -ms.date: 06/20/2016 -ms.openlocfilehash: f10965a8f5f2848f2b942b92577adf3185d8bd3c -ms.sourcegitcommit: 77d9a94dac4c05827ed0663d95e0f9ad35d6682e -ms.translationtype: HT -ms.contentlocale: ja-JP -ms.lasthandoff: 05/24/2018 -ms.locfileid: "34472803" +title: パッケージ、メタパッケージ、フレームワーク +description: パッケージ、メタパッケージ、フレームワークの用語を説明します。 +author: richlander +ms.author: mairaw +ms.date: 06/20/2016 +ms.openlocfilehash: e68c63d26133ac76b718bb3696d16c81bd943dc2 +ms.sourcegitcommit: 6eac9a01ff5d70c6d18460324c016a3612c5e268 +ms.translationtype: HT +ms.contentlocale: ja-JP +ms.lasthandoff: 09/16/2018 +ms.locfileid: "45597689" --- # パッケージ、メタパッケージ、フレームワーク @@ -56,7 +56,7 @@ ms.locfileid: "34472803" メタパッケージは、統合して意味をなすパッケージ セットを記述するための NuGet パッケージの規則です。 メタパッケージでは、パッケージ間に依存関係を設定して、パッケージ セットを表現します。 メタパッケージでは必要に応じて、フレームワークを指定して、このパッケージ セットのフレームワークを確立することができます。 -.NET Core ツールの以前のバージョンは (project.json ツールと csproj-based ツールの両方)、既定では、フレームワークとメタパッケージの両方を指定していました。 ただし、現時点では、各メタパッケージがターゲット フレームワークに関連付けられるように、ターゲット フレームワークによってメタパッケージが暗黙的に参照されます。 たとえば、`netstandard1.6` フレームワークは NetStandard.Library バージョン 1.6.0 メタパッケージを参照します。 同様に、`netcoreapp1.1` フレームワークは Microsoft.NETCore.App バージョン 1.1.0 メタパッケージを参照します。 詳細については、「[Implicit metapackage package reference in the .NET Core SDK](https://github.com/dotnet/core/blob/master/release-notes/1.0/sdk/1.0-rc3-implicit-package-refs.md)」 (.NET Core SDK のメタパッケージの暗黙的パッケージ参照) を参照してください。 +.NET Core ツールの以前のバージョンは (project.json ツールと csproj-based ツールの両方)、既定では、フレームワークとメタパッケージの両方を指定していました。 ただし、現時点では、各メタパッケージがターゲット フレームワークに関連付けられるように、ターゲット フレームワークによってメタパッケージが暗黙的に参照されます。 たとえば、`netstandard1.6` フレームワークは NetStandard.Library バージョン 1.6.0 メタパッケージを参照します。 同様に、`netcoreapp2.1` フレームワークは Microsoft.NETCore.App バージョン 2.1.0 メタパッケージを参照します。 詳細については、「[Implicit metapackage package reference in the .NET Core SDK](https://github.com/dotnet/core/blob/master/release-notes/1.0/sdk/1.0-rc3-implicit-package-refs.md)」 (.NET Core SDK のメタパッケージの暗黙的パッケージ参照) を参照してください。 フレームワークをターゲットにし、メタパッケージを暗黙的に参照することは、各依存パッケージの参照を 1 つのジェスチャとして追加することを実質的に意味します。 これらのパッケージのライブラリはすべて、IntelliSense (または同様のエクスペリエンス) とアプリの公開で利用できます。 diff --git a/docs/core/porting/index.md b/docs/core/porting/index.md index 1712ffb8dc1..8fffe0a4f25 100644 --- a/docs/core/porting/index.md +++ b/docs/core/porting/index.md @@ -1,15 +1,15 @@ --- -title: .NET Framework から .NET Core への移植 -description: 移植プロセスを理解し、.NET Framework プロジェクトを .NET Core に移植する際に役立つツールを確認します。 -author: cartermp -ms.author: mairaw -ms.date: 06/20/2016 -ms.openlocfilehash: bf4f50ca915f21cdda6b99ae6bdf9e837eca3ae7 -ms.sourcegitcommit: 3d5d33f384eeba41b2dff79d096f47ccc8d8f03d -ms.translationtype: HT -ms.contentlocale: ja-JP -ms.lasthandoff: 05/04/2018 -ms.locfileid: "33210083" +title: .NET Framework から .NET Core への移植 +description: 移植プロセスを理解し、.NET Framework プロジェクトを .NET Core に移植する際に役立つツールを確認します。 +author: cartermp +ms.author: mairaw +ms.date: 06/20/2016 +ms.openlocfilehash: d273b3abe46de59aa55b5b9a531d3c572a065124 +ms.sourcegitcommit: 586dbdcaef9767642436b1e4efbe88fb15473d6f +ms.translationtype: HT +ms.contentlocale: ja-JP +ms.lasthandoff: 10/06/2018 +ms.locfileid: "48835393" --- # .NET Framework から .NET Core への移植 @@ -27,7 +27,7 @@ ms.locfileid: "33210083" これにより、.NET Core が特定の API をサポートできない場合に、.NET Framework 固有のターゲットに対して API の代替を確実に使用できます。 -3. [API Portability Analyzer ツール](https://github.com/Microsoft/dotnet-apiport/)使用して、アセンブリを分析し、その結果に基づいて移植を行う計画を作成します。 +3. [.NET Portability Analyzer](../../standard/analyzers/portability-analyzer.md)使用して、アセンブリを分析し、その結果に基づいて移植を行う計画を作成します。 API Portability Analyzer ツールは、コンパイル済みアセンブリを分析し、レポートを生成します。このレポートには、移植性の概要と、.NET Core ではサポートされていない使用中の各 API の内訳が示されます。 このレポートをコードベースの分析と共に使用して、コードを移植する方法の計画を作成します。 diff --git a/docs/core/tools/csproj.md b/docs/core/tools/csproj.md index 18bef5cf32d..bb2f88102cc 100644 --- a/docs/core/tools/csproj.md +++ b/docs/core/tools/csproj.md @@ -4,12 +4,12 @@ description: 既存の csproj ファイルと .NET Core の csproj ファイル author: blackdwarf ms.author: mairaw ms.date: 09/22/2017 -ms.openlocfilehash: d868eb689af1d87ea2adb1f0069345cbb8195af7 -ms.sourcegitcommit: 6eac9a01ff5d70c6d18460324c016a3612c5e268 +ms.openlocfilehash: 1fd264da2863fbeb88900be0f6fe000acac08a09 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/17/2018 -ms.locfileid: "45646377" +ms.lasthandoff: 09/27/2018 +ms.locfileid: "47216917" --- # .NET Core の csproj 形式に追加されたもの @@ -83,11 +83,11 @@ csproj では、プロジェクトから既定の glob を削除し、多様な これらの csproj 変更でプロジェクト ファイルが大幅に簡素化されますが、SDK とそのターゲットが追加されたとき、MSBuild と同様にプロジェクト全体を表示すると便利なことがあります。 [`dotnet msbuild`](dotnet-msbuild.md) コマンドの [`/pp` スイッチ](/visualstudio/msbuild/msbuild-command-line-reference#preprocess)でプロジェクトを事前処理します。インポートされるファイル、そのソース、ビルドに対するその貢献が、実際にプロジェクトをビルドすることなく、表示されます。 -`dotnet msbuild /pp:fullproject.xml` +`dotnet msbuild -pp:fullproject.xml` プロジェクトにターゲット フレームワークが複数存在する場合、MSBuild プロパティとして指定し、1 つだけにコマンドの結果を集中させてください。 -`dotnet msbuild /p:TargetFramework=netcoreapp2.0 /pp:fullproject.xml` +`dotnet msbuild -p:TargetFramework=netcoreapp2.0 -pp:fullproject.xml` ## 追加 @@ -265,3 +265,37 @@ nuget.exe および Visual Studio パッケージ マネージャーで強制す ### NuspecProperties キー=値ペアのセミコロン区切りの一覧。 + +## AssemblyInfo プロパティ +通常、*AssemblyInfo* ファイル内に存在していた[アセンブリ属性](../../framework/app-domains/set-assembly-attributes.md)は、プロパティから自動的に生成されるようになりました。 + +### 属性ごとのプロパティ + +次の表に示すように、各属性にはコンテンツを制御するプロパティと生成を無効にするプロパティがあります。 + +| 属性 | プロパティ | 無効にするプロパティ | +|----------------------------------------------------------------|------------------------|-------------------------------------------------| +| | `Company` | `GenerateAssemblyCompanyAttribute` | +| | `Configuration` | `GenerateAssemblyConfigurationAttribute` | +| | `Copyright` | `GenerateAssemblyCopyrightAttribute` | +| | `Description` | `GenerateAssemblyDescriptionAttribute` | +| | `FileVersion` | `GenerateAssemblyFileVersionAttribute` | +| | `InformationalVersion` | `GenerateAssemblyInformationalVersionAttribute` | +| | `Product` | `GenerateAssemblyProductAttribute` | +| | `AssemblyTitle` | `GenerateAssemblyTitleAttribute` | +| | `AssemblyVersion` | `GenerateAssemblyVersionAttribute` | +| | `NeutralLanguage` | `GenerateNeutralResourcesLanguageAttribute` | + +メモ: + +* `AssemblyVersion` と `FileVersion` の既定値は、サフィックスなしで `$(Version)` の値を受け取ることです。 たとえば、`$(Version)` が `1.2.3-beta.4` の場合、値は `1.2.3` です。 +* `InformationalVersion` の既定値は、`$(Version)` の値です。 +* プロパティが存在する場合、`InformationalVersion` の末尾には `$(SourceRevisionId)` が付加されます。 `IncludeSourceRevisionInInformationalVersion` を使用して無効にすることができます。 +* NuGet メタデータには、`Copyright` および `Description` プロパティも使用されます。 +* `Configuration` はすべてのビルド プロセスで共有され、設定には `dotnet` コマンドの`--configuration` パラメーターを使用します。 + +### GenerateAssemblyInfo +すべての AssemblyInfo 生成を有効または無効にするブール値。 既定値は `true` です。 + +### GeneratedAssemblyInfoFile +生成されたアセンブリ情報ファイルのパス。 既定値は `$(IntermediateOutputPath)` (obj) ディレクトリ内のファイルです。 diff --git a/docs/core/tools/dotnet-clean.md b/docs/core/tools/dotnet-clean.md index 026a7c042f5..9379c4e5f0f 100644 --- a/docs/core/tools/dotnet-clean.md +++ b/docs/core/tools/dotnet-clean.md @@ -1,21 +1,21 @@ --- -title: dotnet clean コマンド - .NET Core CLI -description: dotnet clean コマンドは現在のディレクトリを消去します。 -author: mairaw -ms.author: mairaw -ms.date: 05/25/2018 -ms.openlocfilehash: 9e68781fe00590f3c8d429631a3f72d525d29fa9 -ms.sourcegitcommit: bbf70abe6b46073148f78cbf0619de6092b5800c -ms.translationtype: HT -ms.contentlocale: ja-JP -ms.lasthandoff: 06/04/2018 -ms.locfileid: "34697032" +title: dotnet clean コマンド - .NET Core CLI +description: dotnet clean コマンドは現在のディレクトリを消去します。 +author: mairaw +ms.author: mairaw +ms.date: 05/25/2018 +ms.openlocfilehash: 5553e4b4423a2d824c05caf7114c47b5f1c20477 +ms.sourcegitcommit: 5bbfe34a9a14e4ccb22367e57b57585c208cf757 +ms.translationtype: HT +ms.contentlocale: ja-JP +ms.lasthandoff: 09/18/2018 +ms.locfileid: "45988336" --- -# dotnet-clean +# dotnet clean [!INCLUDE [topic-appliesto-net-core-all](../../../includes/topic-appliesto-net-core-all.md)] -## name +## 名前 `dotnet clean` - プロジェクトの出力を消去します。 diff --git a/docs/core/tools/dotnet-pack.md b/docs/core/tools/dotnet-pack.md index b424008bafa..d15edc46f5c 100644 --- a/docs/core/tools/dotnet-pack.md +++ b/docs/core/tools/dotnet-pack.md @@ -4,12 +4,12 @@ description: dotnet pack コマンドでは、.NET Core プロジェクトの Nu author: mairaw ms.author: mairaw ms.date: 05/29/2018 -ms.openlocfilehash: 8c2569ec7598b21fe9b673176143d0e54b9eb065 -ms.sourcegitcommit: c7f3e2e9d6ead6cc3acd0d66b10a251d0c66e59d +ms.openlocfilehash: 434f1c97af24d1417cd79edd52b63814fd4c6512 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/08/2018 -ms.locfileid: "44204852" +ms.lasthandoff: 10/01/2018 +ms.locfileid: "47231184" --- # dotnet pack @@ -43,7 +43,7 @@ dotnet pack [-h|--help] 既定では、`dotnet pack` は最初にプロジェクトをビルドします。 この動作を避けたい場合は、`--no-build` オプションを渡します。 このオプションは、コードが既にビルドされていることがわかっている場合の継続的インテグレーション (CI) ビルド シナリオで役立つことがよくあります。 -パッキング プロセスのために `dotnet pack` コマンドに MSBuild のプロパティを使用できます。 詳細については、「[NuGet メタデータ プロパティ](csproj.md#nuget-metadata-properties)」と「[MSBuild コマンド ライン リファレンス](/visualstudio/msbuild/msbuild-command-line-reference)」を参照してください。 「[例](#examples)」のセクションでは、MSBuild の /p スイッチを使用する方法について、2 つの異なるシナリオで説明します。 +パッキング プロセスのために `dotnet pack` コマンドに MSBuild のプロパティを使用できます。 詳細については、「[NuGet メタデータ プロパティ](csproj.md#nuget-metadata-properties)」と「[MSBuild コマンド ライン リファレンス](/visualstudio/msbuild/msbuild-command-line-reference)」を参照してください。 「[例](#examples)」のセクションでは、MSBuild の -p スイッチを使用する方法について、2 つの異なるシナリオで説明します。 [!INCLUDE[dotnet restore note + options](~/includes/dotnet-restore-note-options.md)] @@ -109,6 +109,14 @@ NuGet パッケージにソース ファイルを含めます。 ソース フ コマンドの詳細レベルを設定します。 指定できる値は、`q[uiet]`、`m[inimal]`、`n[ormal]`、`d[etailed]`、および `diag[nostic]` です。 +> [!NOTE] +> Web プロジェクトは既定でパッケージ化可能ではありません。 既定の動作をオーバーライドするには、*.csproj* ファイルに次のプロパティを追加します。 +> ```xml +> +> true +> +> ``` + # [.NET Core 1.x](#tab/netcore1x) `-c|--configuration {Debug|Release}` @@ -173,12 +181,12 @@ NuGet パッケージにソース ファイルを含めます。 ソース フ `PackageVersion` MSBuild プロパティで `2.1.0` にパッケージ バージョンを設定します。 -`dotnet pack /p:PackageVersion=2.1.0` +`dotnet pack -p:PackageVersion=2.1.0` プロジェクトを特定の[ターゲット フレームワーク](../../standard/frameworks.md)用にパックします。 -`dotnet pack /p:TargetFrameworks=net45` +`dotnet pack -p:TargetFrameworks=net45` プロジェクトをパックして、復元操作の特定のランタイム (Windows 10) を使用します(.NET Core SDK 2.0 以降のバージョン)。 -`dotnet pack --runtime win10-x64` \ No newline at end of file +`dotnet pack --runtime win10-x64` diff --git a/docs/core/tools/global-tools-how-to-create.md b/docs/core/tools/global-tools-how-to-create.md new file mode 100644 index 00000000000..0f18736fa22 --- /dev/null +++ b/docs/core/tools/global-tools-how-to-create.md @@ -0,0 +1,195 @@ +--- +title: .NET Core グローバル ツールの作成方法 +description: グローバル ツールを作成する方法について説明します。 グローバル ツールは、.NET Core CLI を介してインストールされるコンソール アプリケーションです。 +author: Thraka +ms.author: adegeo +ms.date: 08/22/2018 +ms.openlocfilehash: 3860aad5e2c13714298d50bb9ac10daec3aadf01 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 +ms.translationtype: HT +ms.contentlocale: ja-JP +ms.lasthandoff: 09/28/2018 +ms.locfileid: "47231217" +--- +# .NET Core CLI を使用して .NET Core グローバル ツールを作成する + +この記事では、.NET Core グローバル ツールを作成してパッケージ化する方法について説明します。 .NET Core CLI を使用すると、他のユーザーが簡単にインストールして実行できるコンソール アプリケーションをグローバル ツールとして作成できます。 .NET Core グローバル ツールは、.NET Core CLI からインストールされる NuGet パッケージです。 グローバル ツールの詳細については、「[.NET Core Global Tools overview][global-tool-info]」(.NET Core グローバル ツールの概要) を参照してください。 + +[!INCLUDE [topic-appliesto-net-core-21plus.md](../../../includes/topic-appliesto-net-core-21plus.md)] + +## プロジェクトを作成する + +この記事では、プロジェクトの作成と管理に .NET Core CLI を使用します。 + +ここでの例のツールは、ASCII ボットを生成してメッセージを出力するコンソール アプリケーションです。 まず、新しい .NET Core コンソール アプリケーションを作成します。 + +```console +dotnet new console -o botsay +``` + +前のコマンドで作成した `botsay` ディレクトリに移動します。 + +## コードの追加 + +`vim` や [Visual Studio Code](https://code.visualstudio.com/) など、使い慣れたテキスト エディターで `Program.cs` ファイルを開きます。 + +次の `using` ディレクティブをファイルの先頭に追加すると、アプリケーションのバージョン情報を表示するコードを短くすることができます。 + +```csharp +using System.Reflection; +``` + +次に、`Main` メソッドに移動します。 メソッドを次のコードに置き換えて、アプリケーションのコマンドライン引数を処理します。 引数が渡されなかった場合、短いヘルプ メッセージが表示されます。 それ以外の場合、それらの引数はすべて文字列に変換され、ボットで出力されます。 + +```csharp +static void Main(string[] args) +{ + if (args.Length == 0) + { + var versionString = Assembly.GetEntryAssembly() + .GetCustomAttribute() + .InformationalVersion + .ToString(); + + Console.WriteLine($"botsay v{versionString}"); + Console.WriteLine("-------------"); + Console.WriteLine("\nUsage:"); + Console.WriteLine(" botsay "); + return; + } + + ShowBot(string.Join(' ', args)); +} +``` + +### ボットを作成する + +次に、文字列パラメーターを受け取る `ShowBot` という新しいメソッドを追加します。 このメソッドは、メッセージと ASCII ボットを出力します。 ASCII ボットのコードは、[dotnetbot](https://github.com/dotnet/core/blob/master/samples/dotnetsay/Program.cs) サンプルの一部です。 + +```csharp +static void ShowBot(string message) +{ + string bot = $"\n {message}"; + bot += @" + __________________ + \ + \ + .... + ....' + .... + .......... + .............'..'.. + ................'..'..... + .......'..........'..'..'.... + ........'..........'..'..'..... + .'....'..'..........'..'.......'. + .'..................'... ...... + . ......'......... ..... + . _ __ ...... + .. # ## ...... + .... . ....... + ...... ....... ............ + ................ ...................... + ........................'................ + ......................'..'...... ....... + .........................'..'..... ....... + ........ ..'.............'..'.... .......... + ..'..'... ...............'....... .......... + ...'...... ...... .......... ...... ....... + ........... ....... ........ ...... +....... '...'.'. '.'.'.' .... +....... .....'.. ..'..... + .. .......... ..'........ + ............ .............. + ............. '.............. + ...........'.. .'.'............ + ............... .'.'............. + .............'.. ..'..'........... + ............... .'.............. + ......... .............. + ..... +"; + Console.WriteLine(bot); +} +``` + +### ツールをテストする + +プロジェクトを実行して出力を確認します。 次のようにコマンドラインを変えて、異なる結果を表示してみてください。 + +```csharp +dotnet run +dotnet run -- "Hello from the bot" +dotnet run -- hello from the bot +``` + +区切り記号 `--` の後の引数は、すべてアプリケーションに渡されます。 + +## グローバル ツールを設定する + +アプリケーションをパッケージ化してグローバル ツールとして配布する前に、プロジェクト ファイルを変更する必要があります。 `botsay.csproj` ファイルを開き、3 つの新しい XML ノードを `` ノードに追加します。 + +- `` +[必須] アプリケーションがグローバル ツールとしてインストールされるようにパッケージ化されることを示します。 + +- `` +[省略可能] ツールの代替名。指定しない場合、プロジェクト ファイル名に従ってツールのコマンド名が付けられます。 1 つのパッケージに複数のツールを含めることができます。一意のわかりやすい名前を選択すると、同じパッケージ内の他のツールと区別しやすくなります。 + +- `` +[省略可能] NuGet パッケージが生成される場所。 NuGet パッケージは、.NET Core CLI グローバル ツールがツールのインストールに使用するパッケージです。 + +```xml + + + + Exe + netcoreapp2.1 + + true + botsay + ./nupkg + + + + +``` + +`` は省略可能ですが、この例では使用します。 必ず `./nupkg` を設定してください。 + +次に、アプリケーション用の NuGet パッケージを作成します。 + +```console +dotnet pack +``` + +`botsay.1.0.0.nupkg` ファイルは、`botsay.csproj` ファイルの `` XML 値で識別されるフォルダー (この例では `./nupkg` フォルダー) に作成されます。 これにより、インストールとテストが簡単になります。 ツールを公開する場合は、[https://www.nuget.org](https://www.nuget.org) にアップロードしてください。 + +パッケージを用意できたので、そのパッケージからツールをインストールします。 + +```console +dotnet tool install --global --add-source ./nupkg botsay +``` + +`--add-source` パラメーターで、NuGet パッケージの追加のソース フィードとして `./nupkg` フォルダー (ここでは `` フォルダー) を一時的に使用するように .NET CoreCLI に指示します。 グローバル ツールのインストールの詳細については、「[.NET Core Global Tools overview][global-tool-info]」(.NET Core グローバル ツールの概要) を参照してください。 + +インストールが成功すると、ツールの呼び出しに使用したコマンドとインストールされたバージョンを示す、次の例のようなメッセージが表示されます。 + +``` +You can invoke the tool using the following command: botsay +Tool 'botsay' (version '1.0.0') was successfully installed. +``` + +これで、`botsay` を入力してツールから応答を取得できるようになりました。 + +> [!NOTE] +> インストールは成功しても `botsay` コマンドを使用できない場合は、新しい端末を開いて PATH を更新する必要があります。 + +## ツールを削除する + +ツールの実験を完了したら、次のコマンドでツールを削除することができます。 + +```console +dotnet tool uninstall -g botsay +``` + +[global-tool-info]: global-tools.md diff --git a/docs/core/tools/using-ci-with-cli.md b/docs/core/tools/using-ci-with-cli.md index 2d64dcaebf7..41bc65a5c4c 100644 --- a/docs/core/tools/using-ci-with-cli.md +++ b/docs/core/tools/using-ci-with-cli.md @@ -4,12 +4,12 @@ description: .NET Core SDK とそのツールをビルド サーバーで使用 author: guardrex ms.author: mairaw ms.date: 05/18/2017 -ms.openlocfilehash: 0835ffafc6c091c311b03c90f665cbd669cccfe9 -ms.sourcegitcommit: 3c1c3ba79895335ff3737934e39372555ca7d6d0 +ms.openlocfilehash: 207a6740f2a483d532c194b2bf8112898e9c3463 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/06/2018 -ms.locfileid: "43749935" +ms.lasthandoff: 09/29/2018 +ms.locfileid: "47233245" --- # 継続的インテグレーション (CI) で .NET Core SDK とツールを使用する @@ -34,11 +34,13 @@ macOS をご利用の場合、PKG インストーラーをお使いください インストーラー スクリプトは、ビルドの開始時に実行され、必要なバージョンの SDK を取得し、インストールするように自動化されています。 *必要なバージョン*とは、プロジェクトのビルドに必要な SDK のバージョンです。 このスクリプトでは、サーバーのローカル ディレクトリに SDK をインストールし、インストールした場所からツールを実行し、ビルド後にクリーンアップできます (あるいは、CI サービスにクリーンアップさせます)。 これにより、ビルド プロセス全体にカプセル化と分離性が提供されます。 インストール スクリプト参照は [dotnet-install](dotnet-install-script.md) トピックにあります。 > [!NOTE] +> **Azure DevOps Services** +> > インストーラー スクリプトの使用時、ネイティブ依存性は自動的にはインストールされません。 オペレーティング システムにネイティブ依存性がない場合、それをインストールする必要があります。 前提条件の一覧は [.NET Core ネイティブ前提条件](https://github.com/dotnet/core/blob/master/Documentation/prereqs.md)トピックをご覧ください。 ## CI セットアップ例 -このセクションでは、PowerShell またはバッシュ スクリプトを利用した手動セットアップについて説明し、SaaS (サービスとしてのソフトウェア) CI (継続的インテグレーション) ソリューションをいくつか紹介します。 SaaS CI ソリューションとしては、[Travis CI](https://travis-ci.org/)、[AppVeyor](https://www.appveyor.com/)、[Visual Studio Team Services Build](https://docs.microsoft.com/vsts/build-release/index) を取り上げます。 +このセクションでは、PowerShell またはバッシュ スクリプトを利用した手動セットアップについて説明し、SaaS (サービスとしてのソフトウェア) CI (継続的インテグレーション) ソリューションをいくつか紹介します。 対象となる SaaS CI ソリューションは [Travis CI](https://travis-ci.org/)、[AppVeyor](https://www.appveyor.com/)、および [Build](https://docs.microsoft.com/azure/devops/build-release/index) です。 ### 手動セットアップ @@ -142,16 +144,16 @@ install: # See appveyor.yml example for install script ``` -### Visual Studio Team Services (VSTS) +### Azure DevOps Services -以下のいずれかの手法で .NET Core プロジェクトをビルドするように、Visual Studio Team Services (VSTS) を構成します。 +以下のいずれかの手法で .NET Core プロジェクトをビルドするように Azure DevOps Services を構成します。 1. コマンドを利用し、[手動セットアップ手順](#manual-setup)からスクリプトを実行します。 -1. .NET Core ツールを使用するように構成されたいくつかの VSTS 組み込みビルド タスクで構成されるビルドを作成します。 +1. .NET Core ツールを使用するように構成されたいくつかの Azure DevOps Services 組み込みビルド タスクで構成されるビルドを作成します。 -いずれのソリューションも有効です。 ツールはビルドの一部としてダウンロードしているので、手動セットアップ スクリプトを使用し、取得したツールのバージョンを管理します。 ビルドはスクリプトから実行されます。そのスクリプトを作成する必要があります。 このトピックでは、手動オプションについてのみ説明します。 VSTS ビルド タスクでビルドを作成する方法については、VSTS の「[Continuous integration and deployment](https://docs.microsoft.com/vsts/build-release/index)」 (継続的インテグレーションと展開) トピックを参照してください。 +いずれのソリューションも有効です。 ツールはビルドの一部としてダウンロードしているので、手動セットアップ スクリプトを使用し、取得したツールのバージョンを管理します。 ビルドはスクリプトから実行されます。そのスクリプトを作成する必要があります。 このトピックでは、手動オプションについてのみ説明します。 Azure DevOps Services ビルド タスクでビルドを作成する方法については、Azure DevOps Services の[継続的インテグレーションと展開](https://docs.microsoft.com/azure/devops/build-release/index)に関するトピックを参照してください。 -VSTS で手動セットアップ スクリプトを使用するには、新しいビルド定義を作成し、ビルド手順で実行するスクリプトを指定します。 それには VSTS ユーザー インターフェイスを使います。 +Azure DevOps Services で手動セットアップ スクリプトを使用するには、新しいビルド定義を作成し、ビルド手順で実行するスクリプトを指定します。 これは Azure DevOps Services ユーザー インターフェイスを使用して実行できます。 1. 最初に新しいビルド定義を作成します。 作成するビルドの種類を定義するためのオプションを指定する画面が表示されたら、**[空]** オプションを選択します。 @@ -171,7 +173,7 @@ VSTS で手動セットアップ スクリプトを使用するには、新し ## ビルドの調整 -この文書はその大半で .NET Core ツールの取得方法とさまざまな CI サービスの構成方法について説明しています。 .NET Core でコードを調整する (*実際にビルドする*) 方法に関する情報はありません。 ビルド プロセスの構造化方法の選択肢は、ここでは取り上げることができないさまざまな要因に依存します。 [Travis CI](https://travis-ci.org/)、[AppVeyor](https://www.appveyor.com/)、[VSTS](https://docs.microsoft.com/vsts/build-release/index) でビルドを調整する方法については、それぞれの文書に記載されている資料とサンプルをご覧ください。 +この文書はその大半で .NET Core ツールの取得方法とさまざまな CI サービスの構成方法について説明しています。 .NET Core でコードを調整する (*実際にビルドする*) 方法に関する情報はありません。 ビルド プロセスの構造化方法の選択肢は、ここでは取り上げることができないさまざまな要因に依存します。 [Travis CI](https://travis-ci.org/)、[AppVeyor](https://www.appveyor.com/)、[Azure DevOps Services](https://docs.microsoft.com/azure/devops/build-release/index) でビルドを調整する方法については、それぞれの文書に記載されている資料とサンプルを参照してください。 .NET Core ツールを利用して .NET Core コードのビルド プロセスを構造化するとき、通常、2 つの手法があります。MSBuild を直接利用するか、.NET Core コマンドライン コマンドを利用します。 いずれの手法を採用するかは、手法と複雑性との兼ね合いで使いやすいものを選択してください。 MSBuild を利用すれば、タスクやターゲットとしてビルド プロセスを表現できますが、MSBuild プロジェクト ファイルの構文は複雑で、学習の難易度が上がります。 .NET Core コマンドライン ツールはおそらく、使い方がより単純です。ただし、`bash` や PowerShell のようなスクリプト記述言語でオーケストレーション ロジックを記述する必要があります。 diff --git a/docs/core/tutorials/using-with-xplat-cli.md b/docs/core/tutorials/using-with-xplat-cli.md index 150e69c6e1a..e81c6cd5a3f 100644 --- a/docs/core/tutorials/using-with-xplat-cli.md +++ b/docs/core/tutorials/using-with-xplat-cli.md @@ -3,14 +3,14 @@ title: CLI を使用する .NET Core に関する概要 description: Windows、Linux、または macOS の .NET Core での、.NET Core コマンド ライン インターフェイス (CLI) の使用方法を段階的に説明するチュートリアル。 author: cartermp ms.author: mairaw -ms.date: 03/08/2017 +ms.date: 09/10/2018 ms.technology: dotnet-cli -ms.openlocfilehash: 5ec7168ebc2ee4fc428d1ab520e986842f111ca7 -ms.sourcegitcommit: c7f3e2e9d6ead6cc3acd0d66b10a251d0c66e59d +ms.openlocfilehash: b31a0324c0d762e9898c681cc6581b3860d41f89 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/08/2018 -ms.locfileid: "44200318" +ms.lasthandoff: 09/29/2018 +ms.locfileid: "47203762" --- # Windows/Linux/macOS の .NET Core でのコマンド ラインの使用に関する概要 @@ -20,7 +20,7 @@ ms.locfileid: "44200318" ## 必須コンポーネント -- [.NET Core SDK 1.0](https://www.microsoft.com/net/download/core)。 +- [.NET Core SDK 2.1](https://www.microsoft.com/net/download/core). - ユーザーが選んだテキスト エディターまたはコード エディター。 ## Hello コンソール アプリ @@ -31,7 +31,6 @@ GitHub の dotnet/samples レポジトリから、[サンプル コードを表 ```console $ dotnet new console -$ dotnet restore $ dotnet run ``` @@ -60,13 +59,12 @@ $ dotnet run [!INCLUDE[DotNet Restore Note](~/includes/dotnet-restore-note.md)] -2. `$ dotnet restore` + `dotnet new` は [`dotnet restore`](../tools/dotnet-restore.md) を暗黙的に呼び出します。 `dotnet restore` は、[NuGet](https://www.nuget.org/) (.NET パッケージ マネージャー) を呼び出して依存関係ツリーを復元します。 NuGet は、*Hello.csproj* ファイルを分析し、ファイルに記載されている依存関係をダウンロードし (またはコンピューターのキャッシュから取得し)、サンプルをコンパイルして実行するために必要な *obj/project.assets.json* ファイルを記述します。 + + > [!IMPORTANT] + > .NET Core 1.x バージョンの SDK を使用している場合は、`dotnet new` の呼び出し後に `dotnet restore` を自分で呼び出す必要があります。 - [`dotnet restore`](../tools/dotnet-restore.md) は、[NuGet](https://www.nuget.org/) (.NET パッケージ マネージャー) を参照して依存関係のツリーを復元します。 NuGet は、*Hello.csproj* ファイルを分析し、ファイルに記載されている依存関係をダウンロードして (またはコンピューターのキャッシュから取得して)、*obj/project.assets.json* ファイルを書き込みます。 *project.assets.json* ファイルをコンパイルして実行できる必要があります。 - - *project.assets.json* ファイルは、NuGet の依存関係およびアプリについて記述するその他の情報のグラフの永続的で完全なセットです。 このファイルは、[`dotnet build`](../tools/dotnet-build.md) や [`dotnet run`](../tools/dotnet-run.md) などの他のツールによって読み取られ、これらのツールが NuGet の依存関係とバインド解決の正しいセットでソース コードを処理できるようにします。 - -3. `$ dotnet run` +2. `$ dotnet run` [`dotnet run`](../tools/dotnet-run.md) は、[`dotnet build`](../tools/dotnet-build.md) を呼び出してビルド ターゲットがビルドされていることを確認した後、`dotnet ` を呼び出してターゲット アプリケーションを実行します。 @@ -75,10 +73,9 @@ $ dotnet run Hello World! ``` - [`dotnet build`](../tools/dotnet-build.md) を実行し、ビルド コンソール アプリケーションを実行しないでコードをコンパイルすることもできます。 これで、Windows で `dotnet bin\Debug\netcoreapp1.0\Hello.dll` を使用して (Windows 以外のシステムの場合は `/` を使用して) 実行できる DLL ファイルとしてアプリケーションがコンパイルされます。 アプリケーションには引数を指定することもできます。それについてはこのトピックの後半で説明します。 - + [`dotnet build`](../tools/dotnet-build.md) を実行し、ビルド コンソール アプリケーションを実行しないでコードをコンパイルすることもできます。 これで、Windows で `dotnet bin\Debug\netcoreapp2.1\Hello.dll` を使用して (Windows 以外のシステムの場合は `/` を使用して) 実行できる DLL ファイルとしてアプリケーションがコンパイルされます。 アプリケーションには引数を指定することもできます。それについてはこのトピックの後半で説明します。 ```console - $ dotnet bin\Debug\netcoreapp1.0\Hello.dll + $ dotnet bin\Debug\netcoreapp2.1\Hello.dll Hello World! ``` diff --git a/docs/core/versions/selection.md b/docs/core/versions/selection.md index 79540c49ede..205673735ca 100644 --- a/docs/core/versions/selection.md +++ b/docs/core/versions/selection.md @@ -4,12 +4,12 @@ description: .NET Core がお使いのブログラムのランタイム バー author: billwagner ms.author: wiwagn ms.date: 06/27/2018 -ms.openlocfilehash: 21697aa773abfbd88288d47323402a48c51d69ae -ms.sourcegitcommit: c7f3e2e9d6ead6cc3acd0d66b10a251d0c66e59d +ms.openlocfilehash: 28a76cc17346c40517a21e8dc902bd6c2a84597f +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/08/2018 -ms.locfileid: "44204865" +ms.lasthandoff: 09/27/2018 +ms.locfileid: "47233205" --- # .NET Core のバージョンの選択 @@ -31,7 +31,12 @@ ms.locfileid: "44204865" ## SDK はインストールされている最新バージョンを使用する -SDK コマンドには `dotnet new`、.、または、`dotnet run` が含まれています。 `dotnet` CLI の場合、どのコマンドに対しても SDK バージョンを選択する必要があります。 .NET Core CLI では既定で、コンピューターにインストールされている最新の SDK が使用されます。 使用しているプロジェクトのターゲットが .NET Core Runtime 2.0 の場合でも、.NET Core SDK v2.1.301 がインストールされているとき、.NET Core SDK v2.1.301 が使用されます。 最新のプレビュー バージョンと共にリリース バージョンを使用することになります。 以前のバージョンの .NET Core ランタイムをターゲットにしているとき、SDK の最新の機能と機能改善を活用できます。 すべてのプロジェクトに同じ SDK ツールを使用し、異なるプロジェクトで複数のランタイム バージョンの .NET Core をターゲットにできます。 +SDK コマンドには `dotnet new` または `dotnet run` が含まれています。 `dotnet` CLI の場合、どの dotnet コマンドに対しても SDK バージョンを選択する必要があります。 以下のような場合でも、.NET Core CLI では既定でマシンにインストールされている最新の SDK が使用されます。 + +* プロジェクトが以前のバージョンをターゲットとしている。 +* 最新バージョンがプレビュー バージョンである。 + +アプリが以前のバージョンの .NET Core ランタイムをターゲットにしている場合でも、SDK の最新の機能と機能改善を利用できます。 すべてのプロジェクトに同じ SDK ツールを使用し、異なるプロジェクトで複数のランタイム バージョンの .NET Core をターゲットにできます。 まれに、以前のバージョンの SDK を使用する必要がある場合があります。 そのバージョンは [*global.json* ファイル](../tools/global-json.md)で指定します。 "最新版を使用する" というポリシーは、インストールされている最新版より以前のバージョンの .NET Core SDK を指定するには *global.json* を使用することを意味します。 diff --git a/docs/csharp/event-pattern.md b/docs/csharp/event-pattern.md index c60e4b40e05..71dd66be4d7 100644 --- a/docs/csharp/event-pattern.md +++ b/docs/csharp/event-pattern.md @@ -1,14 +1,14 @@ --- -title: 標準的な .NET イベント パターン -description: .NET イベント パターンに関する情報を提供するほか、標準的なイベント ソースを作成し、標準的なイベントをコードでサブスクライブおよび処理する方法について説明します。 -ms.date: 06/20/2016 -ms.assetid: 8a3133d6-4ef2-46f9-9c8d-a8ea8898e4c9 -ms.openlocfilehash: 9bd9f71726647966dd1e4426b260484decb048c6 -ms.sourcegitcommit: d955cb4c681d68cf301d410925d83f25172ece86 -ms.translationtype: HT -ms.contentlocale: ja-JP -ms.lasthandoff: 06/07/2018 -ms.locfileid: "34827249" +title: 標準的な .NET イベント パターン +description: .NET イベント パターンに関する情報を提供するほか、標準的なイベント ソースを作成し、標準的なイベントをコードでサブスクライブおよび処理する方法について説明します。 +ms.date: 06/20/2016 +ms.assetid: 8a3133d6-4ef2-46f9-9c8d-a8ea8898e4c9 +ms.openlocfilehash: 0b10c440f4d05533032aa94819ec879f6a1ca2a4 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 +ms.translationtype: HT +ms.contentlocale: ja-JP +ms.lasthandoff: 09/29/2018 +ms.locfileid: "47399951" --- # 標準的な .NET イベント パターン @@ -49,7 +49,7 @@ void OnEventRaised(object sender, EventArgs args); [!code-csharp[FileSearxcher](../../samples/csharp/events/Program.cs#FileSearcherV1 "Create the initial file searcher")] -## フィールドのように使用するイベントの定義と発生 +## フィールドのように使用するイベントの定義と発生 クラスにイベントを追加する最も簡単な方法は、上記の例のように、そのイベントをパブリック フィールドとして宣言することです。 diff --git a/docs/csharp/getting-started/index.md b/docs/csharp/getting-started/index.md index 49b104cfa68..8c6f8ccb94c 100644 --- a/docs/csharp/getting-started/index.md +++ b/docs/csharp/getting-started/index.md @@ -7,12 +7,12 @@ helpviewer_keywords: author: rpetrusha ms.author: ronpet ms.date: 08/23/2017 -ms.openlocfilehash: aa34c181073d089d137ac0ef64c85c8fe2772093 -ms.sourcegitcommit: 5bbfe34a9a14e4ccb22367e57b57585c208cf757 +ms.openlocfilehash: 73bf7ca1f05bd388239d970fcc6e33bf30810111 +ms.sourcegitcommit: 586dbdcaef9767642436b1e4efbe88fb15473d6f ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/17/2018 -ms.locfileid: "45972531" +ms.lasthandoff: 10/06/2018 +ms.locfileid: "48837894" --- # C\# の使用を開始する diff --git a/docs/csharp/language-reference/keywords/formatting-numeric-results-table.md b/docs/csharp/language-reference/keywords/formatting-numeric-results-table.md index 173b0c740d7..b74b590126c 100644 --- a/docs/csharp/language-reference/keywords/formatting-numeric-results-table.md +++ b/docs/csharp/language-reference/keywords/formatting-numeric-results-table.md @@ -1,38 +1,60 @@ --- title: 数値結果テーブルの書式設定 (C# リファレンス) -ms.date: 07/20/2015 +description: C# の標準の数値書式指定文字列について説明します +ms.date: 09/20/2018 helpviewer_keywords: - formatting [C#] - numeric formatting [C#] - String.Format method -- Console.Write method ms.assetid: 120ba537-4448-4c62-8676-7a8fdd98f496 -ms.openlocfilehash: 8d034955d5d5d31788eafc0c21246451d7fd1f35 -ms.sourcegitcommit: 2eceb05f1a5bb261291a1f6a91c5153727ac1c19 +ms.openlocfilehash: 6f1cb5b49139cf9661e678cfc0ecc884a2749622 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/04/2018 -ms.locfileid: "43508200" +ms.lasthandoff: 09/28/2018 +ms.locfileid: "47203892" --- # 数値結果テーブルの書式設定 (C# リファレンス) -数値結果の書式を指定するには、 メソッドを使用するか、`String.Format` を呼び出す メソッドまたは メソッドを使用するか、[文字列補間](../tokens/interpolated.md)を使用します。 書式を指定するには、書式指定文字列を使用します。 サポートされる標準の書式指定文字列を次の表に示します。 書式指定文字列は `Axx` という形式になります。この `A` は書式指定子、`xx` は精度指定子です。 書式指定子は、数値に適用する書式の種類を制御し、精度指定子は、書式付き出力の有効桁数または小数点以下の桁数を制御します。 精度指定子の値は 0 から 99 の範囲です。 - - 標準およびカスタム書式指定文字列の詳細については、「[Formatting Types](../../../standard/base-types/formatting-types.md)」(型の書式設定) を参照してください。 - -|書式指定子|説明|使用例|出力| + +次の表は、数値結果の書式を設定するためにサポートされている書式指定子を示しています。 最後の列の書式設定後の結果は、"en-US" に対応します。 + +|書式指定子|説明|使用例|結果| |----------------------|-----------------|--------------|------------| -|C または c|通貨|Console.Write("{0:C}", 2.5);

Console.Write("{0:C}", -2.5);|$2.50

($2.50)| -|D または d|Decimal (10 進数型)|Console.Write("{0:D5}", 25);|00025| -|E または e|指数|Console.Write("{0:E}", 250000);|2.500000E+005| -|F または f|固定小数点|Console.Write("{0:F2}", 25);

Console.Write("{0:F0}", 25);|25.00

25| -|G または g|全般|Console.Write("{0:G}", 2.5);|2.5| -|N または n|数値|Console.Write("{0:N}", 2500000);|2,500,000.00| -|X または x|16 進数|Console.Write("{0:X}", 250);

Console.Write("{0:X}", 0xffff);|FA

FFFF| - -## 参照 - -- [C# リファレンス](../../../csharp/language-reference/index.md) -- [C# プログラミング ガイド](../../../csharp/programming-guide/index.md) -- [標準の数値書式指定文字列](../../../standard/base-types/standard-numeric-format-strings.md) -- [型のリファレンス表](../../../csharp/language-reference/keywords/reference-tables-for-types.md) -- [string](../../../csharp/language-reference/keywords/string.md) +|C または c|通貨|`string s = $"{2.5:C}";`

`string s = $"{-2.5:C}";`|$2.50

($2.50)| +|D または d|Decimal (10 進数型)|`string s = $"{25:D5}";`|00025| +|E または e|指数|`string s = $"{250000:E2}";`|2.50E+005| +|F または f|固定小数点|`string s = $"{2.5:F2}";`

`string s = $"{2.5:F0}";`|2.50

3| +|G または g|全般|`string s = $"{2.5:G}";`|2.5| +|N または n|数字|`string s = $"{2500000:N}";`|2,500,000.00| +|P または p|パーセント|`string s = $"{0.25:P}";`|25.00%| +|R または r|ラウンドトリップ|`string s = $"{2.5:R}";`|2.5| +|X または x|16 進数|`string s = $"{250:X}";`

`string s = $"{0xffff:X}";`|FA

FFFF| + +## コメント + +書式指定子を使用して、書式設定文字列を作成します。 書式設定文字列は `Axx` 形式になります。 + +- `A` は書式指定子であり、数値に適用される書式設定の種類を制御します。 +- `xx` は精度指定子であり、書式設定後の結果の桁数に影響します。 精度指定子の値は 0 から 99 の範囲です。 + +10 進数 ("D"または"d") と 16 進数 ("X"または"x") の形式指定子は、整数型でのみサポートされます。 ラウンドト リップ ("R"または"r") 書式指定子は、 型と 型でのみサポートされます。 + +標準の数値書式指定文字列は、以下をサポートしています。 + +- 全数値型の `ToString` メソッドの一部のオーバーロード。 たとえば、 メソッドおよび メソッドに数値書式指定文字列を指定できます。 + +- .NET の[複合書式設定機能](../../../standard/base-types/composite-formatting.md)。たとえば メソッドでサポートされます。 + +- [挿入文字列](../tokens/interpolated.md)。 + +詳細については、「[標準の数値書式指定文字列](../../../standard/base-types/standard-numeric-format-strings.md)」を参照してください。 + +## 関連項目 + +- [C# リファレンス](../index.md) +- [C# プログラミング ガイド](../../programming-guide/index.md) +- [型のリファレンス表](reference-tables-for-types.md) +- [型の書式設定](../../../standard/base-types/formatting-types.md) +- [複合書式指定](../../../standard/base-types/composite-formatting.md) +- [文字列補間](../tokens/interpolated.md) +- [string](string.md) diff --git a/docs/csharp/language-reference/keywords/is.md b/docs/csharp/language-reference/keywords/is.md index 5cd80582fd9..45f99659db0 100644 --- a/docs/csharp/language-reference/keywords/is.md +++ b/docs/csharp/language-reference/keywords/is.md @@ -7,12 +7,12 @@ f1_keywords: helpviewer_keywords: - is keyword [C#] ms.assetid: bc62316a-d41f-4f90-8300-c6f4f0556e43 -ms.openlocfilehash: 974e0c3ab29da582e7b22c909650a61d179ec3f7 -ms.sourcegitcommit: 2eceb05f1a5bb261291a1f6a91c5153727ac1c19 +ms.openlocfilehash: 8e4103f8e71858ec74c348ee1f675828e6468eb2 +ms.sourcegitcommit: 213292dfbb0c37d83f62709959ff55c50af5560d ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/04/2018 -ms.locfileid: "43523940" +ms.lasthandoff: 09/25/2018 +ms.locfileid: "47170588" --- # is (C# リファレンス) # @@ -128,6 +128,16 @@ C# 7.0 以降では、`is` および [switch](../../../csharp/language-reference 次の例では、型パターンと定数パターンを組み合わせてオブジェクトが `Dice` インスタンスであるかどうかをテストし、そうである場合はサイコロ振り操作の値が 6 であるかどうかをテストします。 [!code-csharp[is#7](../../../../samples/snippets/csharp/language-reference/keywords/is/is-const-pattern7.cs#7)] + +定数パターンを使用して、`null` のチェックを実行できます。 `is` ステートメントで `null` キーワードがサポートされています。 構文は次のとおりです。 + +```csharp + expr is null +``` + +`null` チェックの比較を示す例を次に示します。 + +[!code-csharp[is#11](../../../../samples/snippets/csharp/language-reference/keywords/is/is-const-pattern11.cs#11)] ### var パターン diff --git a/docs/csharp/language-reference/keywords/reference-tables-for-types.md b/docs/csharp/language-reference/keywords/reference-tables-for-types.md index 1f556bd24d7..dc261698e0c 100644 --- a/docs/csharp/language-reference/keywords/reference-tables-for-types.md +++ b/docs/csharp/language-reference/keywords/reference-tables-for-types.md @@ -1,6 +1,6 @@ --- title: 型のリファレンス表 (C# リファレンス) -ms.date: 07/20/2015 +ms.date: 09/21/2018 f1_keywords: - cs.referencetables helpviewer_keywords: @@ -8,36 +8,31 @@ helpviewer_keywords: - types [C#], reference tables - C# language, data types ms.assetid: 1d2b6a9b-31fd-4fa6-a7b2-bfd9c806ac8a -ms.openlocfilehash: 2138bd85740b715466e263020125b367d6036c87 -ms.sourcegitcommit: 2eceb05f1a5bb261291a1f6a91c5153727ac1c19 +ms.openlocfilehash: f75a1cf0b118becd940bd1aa8ac66550d0852773 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/04/2018 -ms.locfileid: "43529911" +ms.lasthandoff: 10/01/2018 +ms.locfileid: "47207336" --- # 型のリファレンス表 (C# リファレンス) 次のリファレンス表に C# の型をまとめて示します。 -- [組み込み型の一覧表](built-in-types-table.md) - -- [整数型](integral-types-table.md) - -- [浮動小数点型](floating-point-types-table.md) - -- [既定値](default-values-table.md) - -- [値型](value-types-table.md) - -- [暗黙の数値変換](implicit-numeric-conversions-table.md) - -- [明示的な数値変換の一覧表](explicit-numeric-conversions-table.md) - -数値型の出力の書式設定については、「[数値結果テーブルの書式設定](formatting-numeric-results-table.md)」を参照してください。 +|テーブル|説明| +|---------|---------| +|[組み込みの型](built-in-types-table.md)|C# の組み込み型と対応する .NET 型を一覧表示します。| +|[整数型](integral-types-table.md)|整数型の概要を示します。| +|[浮動小数点型](floating-point-types-table.md)|浮動小数点型の概要を示します。| +|[値型](value-types-table.md)|C# の値型を一覧表示します。| +|[既定値](default-values-table.md)|C# の値型の既定値を一覧表示します。| +|[暗黙の数値変換](implicit-numeric-conversions-table.md)|C# の数値型の間のサポートされている暗黙的な変換の概要を示します。| +|[明示的な数値変換](explicit-numeric-conversions-table.md)|C# の数値型の間でサポートされている明示的な変換の概要を示します。| +|[数値結果の書式設定](formatting-numeric-results-table.md)|標準の数値書式指定文字列の概要を示します。| ## 関連項目 -- [C# リファレンス](../../language-reference/index.md) +- [C# リファレンス](../index.md) - [C# プログラミング ガイド](../../programming-guide/index.md) - [参照型](reference-types.md) - [値型](value-types.md) \ No newline at end of file diff --git a/docs/csharp/language-reference/keywords/try-catch.md b/docs/csharp/language-reference/keywords/try-catch.md index a3a44f2b592..5887ff01f27 100644 --- a/docs/csharp/language-reference/keywords/try-catch.md +++ b/docs/csharp/language-reference/keywords/try-catch.md @@ -10,12 +10,12 @@ helpviewer_keywords: - catch keyword [C#] - try-catch statement [C#] ms.assetid: cb5503c7-bfa1-4610-8fc2-ddcd2e84c438 -ms.openlocfilehash: 70830b08f9be95422761e0c096071d726a3950c8 -ms.sourcegitcommit: 2eceb05f1a5bb261291a1f6a91c5153727ac1c19 +ms.openlocfilehash: d1fd290444bc7841e32d955a4e7f2134afdbd484 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/04/2018 -ms.locfileid: "43517394" +ms.lasthandoff: 09/27/2018 +ms.locfileid: "47193620" --- # try-catch (C# リファレンス) try-catch ステートメントは、`try` ブロックと、それに続く 1 つ以上の `catch` 句で構成されます。この句にはさまざまな例外のハンドラーを指定します。 diff --git a/docs/csharp/language-reference/operators/or-operator.md b/docs/csharp/language-reference/operators/or-operator.md index 56d2d3a3e45..2226962736b 100644 --- a/docs/csharp/language-reference/operators/or-operator.md +++ b/docs/csharp/language-reference/operators/or-operator.md @@ -8,18 +8,18 @@ helpviewer_keywords: - '| operator [C#]' - binary operator (|) [C#] ms.assetid: 82d6bb78-54c8-40bf-b679-531180ddaf70 -ms.openlocfilehash: d95fe29aa7ffab9938e8edc57999445268fe41a8 -ms.sourcegitcommit: 64f4baed249341e5bf64d1385bf48e3f2e1a0211 +ms.openlocfilehash: 999df9db0819a5f33e21a29b892de0a8854dd5d8 +ms.sourcegitcommit: ad99773e5e45068ce03b99518008397e1299e0d1 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/07/2018 -ms.locfileid: "44085706" +ms.lasthandoff: 09/24/2018 +ms.locfileid: "46706149" --- # | 演算子 (C# リファレンス) 整数型と `bool` には、2 項 `|` 演算子が事前定義されています。 整数型の場合、`|` はそのオペランドのビットごとの OR を計算します。 `bool` オペランドの場合、`|` は、そのオペランドの論理 OR を計算します。つまり、結果は、両方のオペランドが `false` の場合にのみ `false` になります。 ## コメント - バイナリ `|` 演算子は、[条件 OR 演算子] (conditional-or-operator.md) `||` とは対照的に、最初の演算子の値に関係なく、両方の演算子を評価します。 + バイナリ `|` 演算子では、[条件 OR 演算子](conditional-or-operator.md) `||` とは対照的に、最初の演算子の値に関係なく、両方の演算子が評価されます。 ユーザー定義型は `|` 演算子をオーバーロードできます (「[演算子](../../../csharp/language-reference/keywords/operator.md)」を参照)。 diff --git a/docs/csharp/language-reference/tokens/verbatim.md b/docs/csharp/language-reference/tokens/verbatim.md index 6b4391995b0..156f4e1f5ea 100644 --- a/docs/csharp/language-reference/tokens/verbatim.md +++ b/docs/csharp/language-reference/tokens/verbatim.md @@ -10,12 +10,12 @@ helpviewer_keywords: ms.assetid: 89bc7e53-85f5-478a-866d-1cca003c4e8c author: rpetrusha ms.author: ronpet -ms.openlocfilehash: 7dbab5a743b4f9fed759210e8410cd6e3459efac -ms.sourcegitcommit: 6eac9a01ff5d70c6d18460324c016a3612c5e268 +ms.openlocfilehash: 6d6da87159e3ec9184eaa76ad069102204e2fcfc +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/14/2018 -ms.locfileid: "45591400" +ms.lasthandoff: 09/26/2018 +ms.locfileid: "47192231" --- # @ (C# リファレンス) @@ -33,46 +33,9 @@ ms.locfileid: "45591400" [!code-csharp[verbatim3](../../../../samples/snippets/csharp/language-reference/keywords/verbatim1.cs#3)] -1. 名前の競合がある場合に、コンパイラが属性を区別できるようにする。 属性は の派生型です。 通常、その型の名前には **Attribute** サフィックスが含まれます。これは、コンパイラがその規則を強制していない場合でも同様です。 そのため属性は、完全な型名 (たとえば、`[InfoAttribute]`) か、短縮名 (たとえば、`[Info]`) によってコード内から参照できます。 ただし、短縮された 2 つの属性型名が同じである場合、一方の型名に **Attribute** サフィックスが含まれていて、もう一方に含まれていないと、名前の競合が発生します。 たとえば、次のコードでは、`Info` と `InfoAttribute` のどちらの属性が `Example` クラスに適用されるかをコンパイラが判断できないため、コンパイルが失敗します。 +1. 名前の競合がある場合に、コンパイラが属性を区別できるようにする。 属性は の派生クラスです。 通常、その型の名前には **Attribute** サフィックスが含まれます。これは、コンパイラがその規則を強制していない場合でも同様です。 そのため属性は、完全な型名 (たとえば、`[InfoAttribute]`) か、短縮名 (たとえば、`[Info]`) によってコード内から参照できます。 ただし、短縮された 2 つの属性型名が同じである場合、一方の型名に **Attribute** サフィックスが含まれていて、もう一方に含まれていないと、名前の競合が発生します。 たとえば、次のコードでは、`Info` と `InfoAttribute` のどちらの属性が `Example` クラスに適用されるかをコンパイラが判断できないため、コンパイルが失敗します。 詳細については、[CS1614](../compiler-messages/cs1614.md) を参照してください。 - ```csharp - using System; - - [AttributeUsage(AttributeTargets.Class)] - public class Info : Attribute - { - private string information; - - public Info(string info) - { - information = info; - } - } - - [AttributeUsage(AttributeTargets.Method)] - public class InfoAttribute : Attribute - { - private string information; - - public InfoAttribute(string info) - { - information = info; - } - } - - [Info("A simple executable.")] - public class Example - { - [InfoAttribute("The entry point.")] - public static void Main() - { - } - } - ``` - - verbatim 識別子を使用して `Info` 属性を識別すれば、コンパイルは正常に実行されます。 - - [!code-csharp[verbatim4](../../../../samples/snippets/csharp/language-reference/keywords/verbatim4.cs#1)] + [!code-csharp[verbatim4](../../../../samples/snippets/csharp/language-reference/keywords/verbatim2.cs#1)] ## 参照 diff --git a/docs/csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md b/docs/csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md index a6a95d4b38b..8895f16cae8 100644 --- a/docs/csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md +++ b/docs/csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md @@ -2,520 +2,528 @@ title: 非同期タスクまたはタスクの一覧のキャンセル (C#) ms.date: 07/20/2015 ms.assetid: eec32dbb-70ea-4c88-bd27-fa2e34546914 -ms.openlocfilehash: 2aadfccd8b38922b72dfc21daf27f610adffc922 -ms.sourcegitcommit: 6eac9a01ff5d70c6d18460324c016a3612c5e268 +ms.openlocfilehash: 4dc41bc6005a75c06d2c6cc1f3e8d487449b563d +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/17/2018 -ms.locfileid: "45692808" +ms.lasthandoff: 09/29/2018 +ms.locfileid: "47203866" --- # 非同期タスクまたはタスクの一覧のキャンセル (C#) -非同期のアプリケーションが終了するまで待機しない場合、それを取り消すために使用できるボタンを設定できます。 このトピックの例に従うと、1 つの Web サイトのコンテンツまたは Web サイトのリストをダウンロードするアプリケーションにキャンセル ボタンを追加できます。 - - 例では、「[非同期アプリケーションの微調整 (C#)](../../../../csharp/programming-guide/concepts/async/fine-tuning-your-async-application.md)」で説明している UI を使用しています。 - + +非同期のアプリケーションが終了するまで待機しない場合、それを取り消すために使用できるボタンを設定できます。 このトピックの例に従うと、1 つの Web サイトのコンテンツまたは Web サイトのリストをダウンロードするアプリケーションにキャンセル ボタンを追加できます。 + +例では、「[非同期アプリケーションの微調整 (C#)](../../../../csharp/programming-guide/concepts/async/fine-tuning-your-async-application.md)」で説明している UI を使用しています。 + > [!NOTE] -> この例を実行するには、コンピューターに Visual Studio 2012 以降および .NET Framework 4.5 以降がインストールされている必要があります。 - -## タスクのキャンセル - 最初の例では、**キャンセル** ボタンを単一のダウンロード タスクと関連付けます。 アプリケーションがコンテンツをダウンロード中にボタンをクリックすると、ダウンロードは取り消されます。 - -### 例をダウンロードする - 完全な Windows Presentation Foundation (WPF) プロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。ダウンロード後、次の手順に従います。 - -1. ダウンロードしたファイルを圧縮解除し、Visual Studio を起動します。 - -2. メニュー バーで **[ファイル]**、 **[開く]**、 **[プロジェクト/ソリューション]** の順に選択します。 - -3. **[プロジェクトを開く]** ダイアログ ボックスで、圧縮解除したサンプル コードを含むフォルダーを開き、AsyncFineTuningCS のソリューション (.sln) ファイルを開きます。 - -4. **ソリューション エクスプローラー**で、**CancelATask** プロジェクトのショートカット メニューを開き、**[スタートアップ プロジェクトに設定]** をクリックします。 - -5. F5 キーを押してプロジェクトを実行します。 - - Ctrl + F5 キーを押して、デバッグを行わずにプロジェクトを実行します。 - - プロジェクトをダウンロードしない場合は、このトピックの最後の MainWindow.xaml.cs ファイルをレビューできます。 - -### 例のビルド - 次の変更は、Web サイトをダウンロードするアプリケーションに**キャンセル** ボタンを追加します。 この例のダウンロードまたはビルドをしない場合は、このトピックの最後にある「コード例全体」のセクションで最終製品をレビューできます。 アスタリスクはコードの変更点を示しています。 - - この例を自分でビルドするには、「例をダウンロードする」のセクションの詳細な手順の指示に従いますが、**[スタートアップ プロジェクト]** として、**[CancelATask]** の代わりに **[StarterCode]** を選択します。 - - 次の変更点をプロジェクトの MainWindow.xaml.cs ファイルに追加します。 - -1. アクセスするすべてのメソッドのスコープである `CancellationTokenSource` 変数、`cts` を宣言します。 - - ```csharp - public partial class MainWindow : Window - { - // ***Declare a System.Threading.CancellationTokenSource. - CancellationTokenSource cts; - ``` - -2. 次のような**キャンセル** ボタンのイベント ハンドラーのコードを追加します。 ユーザーが取り消しを要求すると、イベント ハンドラーは メソッドを使って `cts` に通知します。 - - ```csharp - // ***Add an event handler for the Cancel button. - private void cancelButton_Click(object sender, RoutedEventArgs e) - { - if (cts != null) - { - cts.Cancel(); - } - } - ``` - -3. **開始**ボタン `startButton_Click` のためのイベント ハンドラーに次の変更を行います。 - - - `CancellationTokenSource`、`cts` をインスタンス化します。 - - ```csharp - // ***Instantiate the CancellationTokenSource. - cts = new CancellationTokenSource(); - ``` - - - 指定された Web サイトのコンテンツをダウンロードする `AccessTheWebAsync` の呼び出しでは、引数として の `cts` プロパティを送ります。 取り消しが要求されると、`Token` プロパティがメッセージを伝達します。 ユーザーがダウンロード操作の取り消しを選択するとメッセージを表示する catch ブロックを追加します。 次のコードは変更点を示しています。 - - ```csharp - try - { - // ***Send a token to carry the message if cancellation is requested. - int contentLength = await AccessTheWebAsync(cts.Token); - resultsTextBox.Text += - String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength); - } - // *** If cancellation is requested, an OperationCanceledException results. - catch (OperationCanceledException) - { - resultsTextBox.Text += "\r\nDownload canceled.\r\n"; - } - catch (Exception) - { - resultsTextBox.Text += "\r\nDownload failed.\r\n"; - } - ``` - -4. `AccessTheWebAsync` では、Web サイトのコンテンツをダウンロードするために 型の `GetAsync` メソッドの オーバーロードを使用します。 2 番目の引数として、`ct` の パラメーターである `AccessTheWebAsync` を渡します。 ユーザーが**キャンセル** ボタンをクリックすると、トークンがメッセージを送信します。 - - 次のコードは、`AccessTheWebAsync` の変更点を示しています。 - - ```csharp - // ***Provide a parameter for the CancellationToken. - async Task AccessTheWebAsync(CancellationToken ct) - { - HttpClient client = new HttpClient(); - - resultsTextBox.Text += - String.Format("\r\nReady to download.\r\n"); - - // You might need to slow things down to have a chance to cancel. - await Task.Delay(250); - - // GetAsync returns a Task. - // ***The ct argument carries the message if the Cancel button is chosen. - HttpResponseMessage response = await client.GetAsync("http://msdn.microsoft.com/library/dd470362.aspx", ct); - - // Retrieve the website contents from the HttpResponseMessage. - byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); - - // The result of the method is the length of the downloaded website. - return urlContents.Length; - } - ``` - -5. プログラムの取り消しをしない場合、次の出力を生成します。 - - ``` - Ready to download. - Length of the downloaded string: 158125. - ``` - - プログラムがコンテンツのダウンロードを終了する前に**キャンセル** ボタンをクリックすると、プログラムは次の出力を生成します。 - - ``` - Ready to download. - Download canceled. - ``` - -## タスクの一覧を取り消す - 前の例を拡張すると、同じ `CancellationTokenSource` のインスタンスを各タスクに関連付けることによって、多数のタスクを取り消すことができます。 **キャンセル** ボタンをクリックすると、完了していないすべてのタスクを取り消します。 - -### 例をダウンロードする - 完全な Windows Presentation Foundation (WPF) プロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。ダウンロード後、次の手順に従います。 - -1. ダウンロードしたファイルを圧縮解除し、Visual Studio を起動します。 - -2. メニュー バーで **[ファイル]**、 **[開く]**、 **[プロジェクト/ソリューション]** の順に選択します。 - -3. **[プロジェクトを開く]** ダイアログ ボックスで、圧縮解除したサンプル コードを含むフォルダーを開き、AsyncFineTuningCS のソリューション (.sln) ファイルを開きます。 - -4. **ソリューション エクスプローラー**で、**CancelAListOfTasks** プロジェクトのショートカット メニューを開き、**[スタートアップ プロジェクトに設定]** をクリックします。 - -5. F5 キーを押してプロジェクトを実行します。 - - Ctrl + F5 キーを押して、デバッグを行わずにプロジェクトを実行します。 - - プロジェクトをダウンロードしない場合は、このトピックの最後の MainWindow.xaml.cs ファイルをレビューできます。 - -### 例のビルド - この例を自分で拡張するには、「例をダウンロードする」のセクションの詳細な手順の指示に従いますが、**[スタートアップ プロジェクト]** として **CancelATask** を選択します。 次の変更点をプロジェクトに追加します。 アスタリスクはプログラムの変更点を示しています。 - -1. Web アドレスのリストを作成するメソッドを追加します。 - - ```csharp - // ***Add a method that creates a list of web addresses. - private List SetUpURLList() - { - List urls = new List - { - "http://msdn.microsoft.com", - "http://msdn.microsoft.com/library/hh290138.aspx", - "http://msdn.microsoft.com/library/hh290140.aspx", - "http://msdn.microsoft.com/library/dd470362.aspx", - "http://msdn.microsoft.com/library/aa578028.aspx", - "http://msdn.microsoft.com/library/ms404677.aspx", - "http://msdn.microsoft.com/library/ff730837.aspx" - }; - return urls; - } - ``` - -2. `AccessTheWebAsync` のメソッドを呼び出します。 - - ```csharp - // ***Call SetUpURLList to make a list of web addresses. - List urlList = SetUpURLList(); - ``` - -3. 次のループを `AccessTheWebAsync` に追加して、リストの各 Web アドレスを処理します。 - - ```csharp - // ***Add a loop to process the list of web addresses. - foreach (var url in urlList) - { - // GetAsync returns a Task. - // Argument ct carries the message if the Cancel button is chosen. - // ***Note that the Cancel button can cancel all remaining downloads. - HttpResponseMessage response = await client.GetAsync(url, ct); - - // Retrieve the website contents from the HttpResponseMessage. - byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); - - resultsTextBox.Text += - String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length); - } - ``` - -4. `AccessTheWebAsync` は長さを表示するため、メソッドは何も返す必要はありません。 return ステートメントを削除し、メソッドの戻り値の型を ではなく に変更します。 - - ```csharp - async Task AccessTheWebAsync(CancellationToken ct) - ``` - - 式の代わりにステートメントを使って、`startButton_Click` からメソッドを呼び出します。 - - ```csharp - await AccessTheWebAsync(cts.Token); - ``` - -5. プログラムの取り消しをしない場合、次の出力を生成します。 - - ``` - Length of the downloaded string: 35939. - - Length of the downloaded string: 237682. - - Length of the downloaded string: 128607. - - Length of the downloaded string: 158124. - - Length of the downloaded string: 204890. - - Length of the downloaded string: 175488. - - Length of the downloaded string: 145790. - - Downloads complete. - ``` - - ダウンロードが完了する前に**キャンセル** ボタンをクリックすると、出力には取り消しの前に完了したダウンロードの長さが含まれています。 - - ``` - Length of the downloaded string: 35939. - - Length of the downloaded string: 237682. - - Length of the downloaded string: 128607. - - Downloads canceled. - ``` - -## コード例全体 - 次のセクションには、前の例の各コードが含まれています。 の参照を追加する必要があることに注意してください。 - - このプロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。 - -### タスクを取り消す例 - 次のコードは、単一のタスクを取り消す例での MainWindow.xaml.cs ファイルの全体です。 - -```csharp -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; - -// Add a using directive and a reference for System.Net.Http. -using System.Net.Http; - -// Add the following using directive for System.Threading. - -using System.Threading; -namespace CancelATask -{ - public partial class MainWindow : Window - { - // ***Declare a System.Threading.CancellationTokenSource. - CancellationTokenSource cts; - - public MainWindow() - { - InitializeComponent(); - } - - private async void startButton_Click(object sender, RoutedEventArgs e) - { - // ***Instantiate the CancellationTokenSource. - cts = new CancellationTokenSource(); - - resultsTextBox.Clear(); - - try - { - // ***Send a token to carry the message if cancellation is requested. - int contentLength = await AccessTheWebAsync(cts.Token); - resultsTextBox.Text += - String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength); - } - // *** If cancellation is requested, an OperationCanceledException results. - catch (OperationCanceledException) - { - resultsTextBox.Text += "\r\nDownload canceled.\r\n"; - } - catch (Exception) - { - resultsTextBox.Text += "\r\nDownload failed.\r\n"; - } - - // ***Set the CancellationTokenSource to null when the download is complete. - cts = null; - } - - // ***Add an event handler for the Cancel button. - private void cancelButton_Click(object sender, RoutedEventArgs e) - { - if (cts != null) - { - cts.Cancel(); - } - } - - // ***Provide a parameter for the CancellationToken. - async Task AccessTheWebAsync(CancellationToken ct) - { - HttpClient client = new HttpClient(); - - resultsTextBox.Text += - String.Format("\r\nReady to download.\r\n"); - - // You might need to slow things down to have a chance to cancel. - await Task.Delay(250); - - // GetAsync returns a Task. - // ***The ct argument carries the message if the Cancel button is chosen. - HttpResponseMessage response = await client.GetAsync("http://msdn.microsoft.com/library/dd470362.aspx", ct); - - // Retrieve the website contents from the HttpResponseMessage. - byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); - - // The result of the method is the length of the downloaded website. - return urlContents.Length; - } - } - - // Output for a successful download: - - // Ready to download. - - // Length of the downloaded string: 158125. - - // Or, if you cancel: - - // Ready to download. - - // Download canceled. -} -``` - -### タスクの一覧を取り消す例 - 次のコードは、タスクの一覧を取り消す例での MainWindow.xaml.cs ファイルの全体です。 - -```csharp -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; - -// Add a using directive and a reference for System.Net.Http. -using System.Net.Http; - -// Add the following using directive for System.Threading. -using System.Threading; - -namespace CancelAListOfTasks -{ - public partial class MainWindow : Window - { - // Declare a System.Threading.CancellationTokenSource. - CancellationTokenSource cts; - - public MainWindow() - { - InitializeComponent(); - } - - private async void startButton_Click(object sender, RoutedEventArgs e) - { - // Instantiate the CancellationTokenSource. - cts = new CancellationTokenSource(); - - resultsTextBox.Clear(); - - try - { - await AccessTheWebAsync(cts.Token); - // ***Small change in the display lines. - resultsTextBox.Text += "\r\nDownloads complete."; - } - catch (OperationCanceledException) - { - resultsTextBox.Text += "\r\nDownloads canceled."; - } - catch (Exception) - { - resultsTextBox.Text += "\r\nDownloads failed."; - } - - // Set the CancellationTokenSource to null when the download is complete. - cts = null; - } - - // Add an event handler for the Cancel button. - private void cancelButton_Click(object sender, RoutedEventArgs e) - { - if (cts != null) - { - cts.Cancel(); - } - } - - // Provide a parameter for the CancellationToken. - // ***Change the return type to Task because the method has no return statement. - async Task AccessTheWebAsync(CancellationToken ct) - { - // Declare an HttpClient object. - HttpClient client = new HttpClient(); - - // ***Call SetUpURLList to make a list of web addresses. - List urlList = SetUpURLList(); - - // ***Add a loop to process the list of web addresses. - foreach (var url in urlList) - { - // GetAsync returns a Task. - // Argument ct carries the message if the Cancel button is chosen. - // ***Note that the Cancel button can cancel all remaining downloads. - HttpResponseMessage response = await client.GetAsync(url, ct); - - // Retrieve the website contents from the HttpResponseMessage. - byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); - - resultsTextBox.Text += - String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length); - } - } - - // ***Add a method that creates a list of web addresses. - private List SetUpURLList() - { - List urls = new List - { - "http://msdn.microsoft.com", - "http://msdn.microsoft.com/library/hh290138.aspx", - "http://msdn.microsoft.com/library/hh290140.aspx", - "http://msdn.microsoft.com/library/dd470362.aspx", - "http://msdn.microsoft.com/library/aa578028.aspx", - "http://msdn.microsoft.com/library/ms404677.aspx", - "http://msdn.microsoft.com/library/ff730837.aspx" - }; - return urls; - } - } - - // Output if you do not choose to cancel: - - //Length of the downloaded string: 35939. - - //Length of the downloaded string: 237682. - - //Length of the downloaded string: 128607. - - //Length of the downloaded string: 158124. - - //Length of the downloaded string: 204890. - - //Length of the downloaded string: 175488. - - //Length of the downloaded string: 145790. - - //Downloads complete. - - // Sample output if you choose to cancel: - - //Length of the downloaded string: 35939. - - //Length of the downloaded string: 237682. - - //Length of the downloaded string: 128607. - - //Downloads canceled. -} -``` - -## 参照 - -- -- -- [Async および Await を使用した非同期プログラミング (C#)](../../../../csharp/programming-guide/concepts/async/index.md) -- [非同期アプリケーションの微調整 (C#)](../../../../csharp/programming-guide/concepts/async/fine-tuning-your-async-application.md) +> この例を実行するには、コンピューターに Visual Studio 2012 以降および .NET Framework 4.5 以降がインストールされている必要があります。 + +## タスクをキャンセルする + +最初の例では、**キャンセル** ボタンを単一のダウンロード タスクと関連付けます。 アプリケーションがコンテンツをダウンロード中にボタンをクリックすると、ダウンロードは取り消されます。 + +### サンプルをダウンロードする + +完全な Windows Presentation Foundation (WPF) プロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。ダウンロード後、次の手順に従います。 + +1. ダウンロードしたファイルを圧縮解除し、Visual Studio を起動します。 + +2. メニュー バーで、**[ファイル]** > **[開く]** > **[プロジェクト/ソリューション]** を選択します。 + +3. **[プロジェクトを開く]** ダイアログ ボックスで、圧縮解除したサンプル コードを含むフォルダーを開き、AsyncFineTuningCS のソリューション (.sln) ファイルを開きます。 + +4. **ソリューション エクスプローラー**で、**CancelATask** プロジェクトのショートカット メニューを開き、**[スタートアップ プロジェクトに設定]** をクリックします。 + +5. **F5** キーを選択してプロジェクトを実行し (または、**Ctrl**+**F5** キーを押してプロジェクトをデバッグなしで実行します)。 + +> [!TIP] +> プロジェクトをダウンロードしない場合は、このトピックの最後の MainWindow.xaml.cs ファイルをレビューできます。 + +### サンプルをビルドする + 次の変更は、Web サイトをダウンロードするアプリケーションに**キャンセル** ボタンを追加します。 この例のダウンロードまたはビルドをしない場合は、このトピックの最後にある「コード例全体」のセクションで最終製品をレビューできます。 アスタリスクはコードの変更点を示しています。 + + この例を自分でビルドするには、「例をダウンロードする」のセクションの詳細な手順の指示に従いますが、**[スタートアップ プロジェクト]** として、**[CancelATask]** の代わりに **[StarterCode]** を選択します。 + + 次の変更点をプロジェクトの MainWindow.xaml.cs ファイルに追加します。 + +1. アクセスするすべてのメソッドのスコープである `CancellationTokenSource` 変数、`cts` を宣言します。 + + ```csharp + public partial class MainWindow : Window + { + // ***Declare a System.Threading.CancellationTokenSource. + CancellationTokenSource cts; + ``` + +2. 次のような**キャンセル** ボタンのイベント ハンドラーのコードを追加します。 ユーザーが取り消しを要求すると、イベント ハンドラーは メソッドを使って `cts` に通知します。 + + ```csharp + // ***Add an event handler for the Cancel button. + private void cancelButton_Click(object sender, RoutedEventArgs e) + { + if (cts != null) + { + cts.Cancel(); + } + } + ``` + +3. **開始**ボタン `startButton_Click` のためのイベント ハンドラーに次の変更を行います。 + + - `CancellationTokenSource`、`cts` をインスタンス化します。 + + ```csharp + // ***Instantiate the CancellationTokenSource. + cts = new CancellationTokenSource(); + ``` + + - 指定された Web サイトのコンテンツをダウンロードする `AccessTheWebAsync` の呼び出しでは、引数として の `cts` プロパティを送ります。 取り消しが要求されると、`Token` プロパティがメッセージを伝達します。 ユーザーがダウンロード操作の取り消しを選択するとメッセージを表示する catch ブロックを追加します。 次のコードは変更点を示しています。 + + ```csharp + try + { + // ***Send a token to carry the message if cancellation is requested. + int contentLength = await AccessTheWebAsync(cts.Token); + resultsTextBox.Text += + String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength); + } + // *** If cancellation is requested, an OperationCanceledException results. + catch (OperationCanceledException) + { + resultsTextBox.Text += "\r\nDownload canceled.\r\n"; + } + catch (Exception) + { + resultsTextBox.Text += "\r\nDownload failed.\r\n"; + } + ``` + +4. `AccessTheWebAsync` では、Web サイトのコンテンツをダウンロードするために 型の `GetAsync` メソッドの オーバーロードを使用します。 2 番目の引数として、`ct` の パラメーターである `AccessTheWebAsync` を渡します。 ユーザーが**キャンセル** ボタンをクリックすると、トークンがメッセージを送信します。 + + 次のコードは、`AccessTheWebAsync` の変更点を示しています。 + + ```csharp + // ***Provide a parameter for the CancellationToken. + async Task AccessTheWebAsync(CancellationToken ct) + { + HttpClient client = new HttpClient(); + + resultsTextBox.Text += + String.Format("\r\nReady to download.\r\n"); + + // You might need to slow things down to have a chance to cancel. + await Task.Delay(250); + + // GetAsync returns a Task. + // ***The ct argument carries the message if the Cancel button is chosen. + HttpResponseMessage response = await client.GetAsync("http://msdn.microsoft.com/library/dd470362.aspx", ct); + + // Retrieve the website contents from the HttpResponseMessage. + byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); + + // The result of the method is the length of the downloaded website. + return urlContents.Length; + } + ``` + +5. プログラムの取り消しをしない場合、次の出力を生成します。 + + ```text + Ready to download. + Length of the downloaded string: 158125. + ``` + + プログラムがコンテンツのダウンロードを終了する前に**キャンセル** ボタンをクリックすると、プログラムは次の出力を生成します。 + + ```text + Ready to download. + Download canceled. + ``` + +## タスクの一覧を取り消す + +前の例を拡張すると、同じ `CancellationTokenSource` のインスタンスを各タスクに関連付けることによって、多数のタスクを取り消すことができます。 **キャンセル** ボタンをクリックすると、完了していないすべてのタスクを取り消します。 + +### サンプルをダウンロードする + +完全な Windows Presentation Foundation (WPF) プロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。ダウンロード後、次の手順に従います。 + +1. ダウンロードしたファイルを圧縮解除し、Visual Studio を起動します。 + +2. メニュー バーで、**[ファイル]** > **[開く]** > **[プロジェクト/ソリューション]** を選択します。 + +3. **[プロジェクトを開く]** ダイアログ ボックスで、圧縮解除したサンプル コードを含むフォルダーを開き、AsyncFineTuningCS のソリューション (.sln) ファイルを開きます。 + +4. **ソリューション エクスプローラー**で、**CancelAListOfTasks** プロジェクトのショートカット メニューを開き、**[スタートアップ プロジェクトに設定]** をクリックします。 + +5. **F5** キーを押してプロジェクトを実行します。 + + **Ctrl**+**F5** キーを押して、デバッグなしでプロジェクトを実行します。 + +プロジェクトをダウンロードしない場合は、このトピックの最後の MainWindow.xaml.cs ファイルをレビューできます。 + +### サンプルをビルドする + +この例を自分で拡張するには、「例をダウンロードする」のセクションの詳細な手順の指示に従いますが、**[スタートアップ プロジェクト]** として **CancelATask** を選択します。 次の変更点をプロジェクトに追加します。 アスタリスクはプログラムの変更点を示しています。 + +1. Web アドレスのリストを作成するメソッドを追加します。 + + ```csharp + // ***Add a method that creates a list of web addresses. + private List SetUpURLList() + { + List urls = new List + { + "http://msdn.microsoft.com", + "http://msdn.microsoft.com/library/hh290138.aspx", + "http://msdn.microsoft.com/library/hh290140.aspx", + "http://msdn.microsoft.com/library/dd470362.aspx", + "http://msdn.microsoft.com/library/aa578028.aspx", + "http://msdn.microsoft.com/library/ms404677.aspx", + "http://msdn.microsoft.com/library/ff730837.aspx" + }; + return urls; + } + ``` + +2. `AccessTheWebAsync` のメソッドを呼び出します。 + + ```csharp + // ***Call SetUpURLList to make a list of web addresses. + List urlList = SetUpURLList(); + ``` + +3. 次のループを `AccessTheWebAsync` に追加して、リストの各 Web アドレスを処理します。 + + ```csharp + // ***Add a loop to process the list of web addresses. + foreach (var url in urlList) + { + // GetAsync returns a Task. + // Argument ct carries the message if the Cancel button is chosen. + // ***Note that the Cancel button can cancel all remaining downloads. + HttpResponseMessage response = await client.GetAsync(url, ct); + + // Retrieve the website contents from the HttpResponseMessage. + byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); + + resultsTextBox.Text += + String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length); + } + ``` + +4. `AccessTheWebAsync` は長さを表示するため、メソッドは何も返す必要はありません。 return ステートメントを削除し、メソッドの戻り値の型を ではなく に変更します。 + + ```csharp + async Task AccessTheWebAsync(CancellationToken ct) + ``` + + 式の代わりにステートメントを使って、`startButton_Click` からメソッドを呼び出します。 + + ```csharp + await AccessTheWebAsync(cts.Token); + ``` + +5. プログラムの取り消しをしない場合、次の出力を生成します。 + + ```text + Length of the downloaded string: 35939. + + Length of the downloaded string: 237682. + + Length of the downloaded string: 128607. + + Length of the downloaded string: 158124. + + Length of the downloaded string: 204890. + + Length of the downloaded string: 175488. + + Length of the downloaded string: 145790. + + Downloads complete. + ``` + + ダウンロードが完了する前に**キャンセル** ボタンをクリックすると、出力には取り消しの前に完了したダウンロードの長さが含まれています。 + + ```text + Length of the downloaded string: 35939. + + Length of the downloaded string: 237682. + + Length of the downloaded string: 128607. + + Downloads canceled. + ``` + +## 完全な例 + +次のセクションには、前の例の各コードが含まれています。 の参照を追加する必要があることに注意してください。 + +このプロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。 + +### 例 - タスクを取り消す + +次のコードは、単一のタスクを取り消す例での MainWindow.xaml.cs ファイルの全体です。 + +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +// Add a using directive and a reference for System.Net.Http. +using System.Net.Http; + +// Add the following using directive for System.Threading. + +using System.Threading; +namespace CancelATask +{ + public partial class MainWindow : Window + { + // ***Declare a System.Threading.CancellationTokenSource. + CancellationTokenSource cts; + + public MainWindow() + { + InitializeComponent(); + } + + private async void startButton_Click(object sender, RoutedEventArgs e) + { + // ***Instantiate the CancellationTokenSource. + cts = new CancellationTokenSource(); + + resultsTextBox.Clear(); + + try + { + // ***Send a token to carry the message if cancellation is requested. + int contentLength = await AccessTheWebAsync(cts.Token); + resultsTextBox.Text += + String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength); + } + // *** If cancellation is requested, an OperationCanceledException results. + catch (OperationCanceledException) + { + resultsTextBox.Text += "\r\nDownload canceled.\r\n"; + } + catch (Exception) + { + resultsTextBox.Text += "\r\nDownload failed.\r\n"; + } + + // ***Set the CancellationTokenSource to null when the download is complete. + cts = null; + } + + // ***Add an event handler for the Cancel button. + private void cancelButton_Click(object sender, RoutedEventArgs e) + { + if (cts != null) + { + cts.Cancel(); + } + } + + // ***Provide a parameter for the CancellationToken. + async Task AccessTheWebAsync(CancellationToken ct) + { + HttpClient client = new HttpClient(); + + resultsTextBox.Text += + String.Format("\r\nReady to download.\r\n"); + + // You might need to slow things down to have a chance to cancel. + await Task.Delay(250); + + // GetAsync returns a Task. + // ***The ct argument carries the message if the Cancel button is chosen. + HttpResponseMessage response = await client.GetAsync("http://msdn.microsoft.com/library/dd470362.aspx", ct); + + // Retrieve the website contents from the HttpResponseMessage. + byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); + + // The result of the method is the length of the downloaded website. + return urlContents.Length; + } + } + + // Output for a successful download: + + // Ready to download. + + // Length of the downloaded string: 158125. + + // Or, if you cancel: + + // Ready to download. + + // Download canceled. +} +``` + +### 例 - タスクの一覧を取り消す + +次のコードは、タスクの一覧を取り消す例での MainWindow.xaml.cs ファイルの全体です。 + +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +// Add a using directive and a reference for System.Net.Http. +using System.Net.Http; + +// Add the following using directive for System.Threading. +using System.Threading; + +namespace CancelAListOfTasks +{ + public partial class MainWindow : Window + { + // Declare a System.Threading.CancellationTokenSource. + CancellationTokenSource cts; + + public MainWindow() + { + InitializeComponent(); + } + + private async void startButton_Click(object sender, RoutedEventArgs e) + { + // Instantiate the CancellationTokenSource. + cts = new CancellationTokenSource(); + + resultsTextBox.Clear(); + + try + { + await AccessTheWebAsync(cts.Token); + // ***Small change in the display lines. + resultsTextBox.Text += "\r\nDownloads complete."; + } + catch (OperationCanceledException) + { + resultsTextBox.Text += "\r\nDownloads canceled."; + } + catch (Exception) + { + resultsTextBox.Text += "\r\nDownloads failed."; + } + + // Set the CancellationTokenSource to null when the download is complete. + cts = null; + } + + // Add an event handler for the Cancel button. + private void cancelButton_Click(object sender, RoutedEventArgs e) + { + if (cts != null) + { + cts.Cancel(); + } + } + + // Provide a parameter for the CancellationToken. + // ***Change the return type to Task because the method has no return statement. + async Task AccessTheWebAsync(CancellationToken ct) + { + // Declare an HttpClient object. + HttpClient client = new HttpClient(); + + // ***Call SetUpURLList to make a list of web addresses. + List urlList = SetUpURLList(); + + // ***Add a loop to process the list of web addresses. + foreach (var url in urlList) + { + // GetAsync returns a Task. + // Argument ct carries the message if the Cancel button is chosen. + // ***Note that the Cancel button can cancel all remaining downloads. + HttpResponseMessage response = await client.GetAsync(url, ct); + + // Retrieve the website contents from the HttpResponseMessage. + byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); + + resultsTextBox.Text += + String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length); + } + } + + // ***Add a method that creates a list of web addresses. + private List SetUpURLList() + { + List urls = new List + { + "http://msdn.microsoft.com", + "http://msdn.microsoft.com/library/hh290138.aspx", + "http://msdn.microsoft.com/library/hh290140.aspx", + "http://msdn.microsoft.com/library/dd470362.aspx", + "http://msdn.microsoft.com/library/aa578028.aspx", + "http://msdn.microsoft.com/library/ms404677.aspx", + "http://msdn.microsoft.com/library/ff730837.aspx" + }; + return urls; + } + } + + // Output if you do not choose to cancel: + + //Length of the downloaded string: 35939. + + //Length of the downloaded string: 237682. + + //Length of the downloaded string: 128607. + + //Length of the downloaded string: 158124. + + //Length of the downloaded string: 204890. + + //Length of the downloaded string: 175488. + + //Length of the downloaded string: 145790. + + //Downloads complete. + + // Sample output if you choose to cancel: + + //Length of the downloaded string: 35939. + + //Length of the downloaded string: 237682. + + //Length of the downloaded string: 128607. + + //Downloads canceled. +} +``` + +## 関連項目 + +- +- +- [Async および Await を使用した非同期プログラミング (C#)](../../../../csharp/programming-guide/concepts/async/index.md) +- [非同期アプリケーションの微調整 (C#)](../../../../csharp/programming-guide/concepts/async/fine-tuning-your-async-application.md) - [非同期のサンプル: アプリケーションの微調整](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea) diff --git a/docs/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md b/docs/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md index 118fd99b201..3763c08e312 100644 --- a/docs/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md +++ b/docs/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md @@ -2,221 +2,223 @@ title: 指定した時間の経過後の非同期タスクのキャンセル (C#) ms.date: 07/20/2015 ms.assetid: 194282c2-399f-46da-a7a6-96674e00b0b3 -ms.openlocfilehash: 33f37b78deb5ffe322e9d01a4dc2dc1301547f49 -ms.sourcegitcommit: 2eceb05f1a5bb261291a1f6a91c5153727ac1c19 +ms.openlocfilehash: b95b87e1e93a9c8f8c74680a917a128d45172ed5 +ms.sourcegitcommit: fb78d8abbdb87144a3872cf154930157090dd933 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/04/2018 -ms.locfileid: "43515947" +ms.lasthandoff: 09/27/2018 +ms.locfileid: "47397346" --- # 指定した時間の経過後の非同期タスクのキャンセル (C#) - メソッドを使用すると、一定の時間が過ぎた後に非同期操作が完了するまで待たない場合に、その操作を取り消しできます。 このメソッドは、`CancelAfter` 式によって指定された時間内に完了しない、関連付けられたタスクの取り消しをスケジュールします。 - - この例では、「[タスクまたはタスクの一覧のキャンセル (C#)](../../../../csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md)」で開発したコードに追加して、Web サイトの一覧をダウンロードして各サイトのコンテンツの長さを表示します。 - + + メソッドを使用すると、一定の時間が過ぎた後に非同期操作が完了するまで待たない場合に、その操作を取り消しできます。 このメソッドは、`CancelAfter` 式によって指定された時間内に完了しない、関連付けられたタスクの取り消しをスケジュールします。 + +この例では、「[タスクまたはタスクの一覧のキャンセル (C#)](../../../../csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md)」で開発したコードに追加して、Web サイトの一覧をダウンロードして各サイトのコンテンツの長さを表示します。 + > [!NOTE] -> この例を実行するには、コンピューターに Visual Studio 2012 以降および .NET Framework 4.5 以降がインストールされている必要があります。 - -## 例をダウンロードする - 完全な Windows Presentation Foundation (WPF) プロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。ダウンロード後、次の手順に従います。 - -1. ダウンロードしたファイルを圧縮解除し、Visual Studio を起動します。 - -2. メニュー バーで **[ファイル]**、 **[開く]**、 **[プロジェクト/ソリューション]** の順に選択します。 - -3. **[プロジェクトを開く]** ダイアログ ボックスで、圧縮解除したサンプル コードを含むフォルダーを開き、AsyncFineTuningCS のソリューション (.sln) ファイルを開きます。 - -4. **ソリューション エクスプローラー**で、**CancelAfterTime** プロジェクトのショートカット メニューを開き、**[スタートアップ プロジェクトに設定]** をクリックします。 - -5. F5 キーを押してプロジェクトを実行します。 - - Ctrl + F5 キーを押して、デバッグを行わずにプロジェクトを実行します。 - -6. プログラムを複数回実行して、出力がすべての Web サイトの出力を示したり、どの Web サイトの出力も示さなかったり、一部の Web サイトの出力を示したりすることを確認します。 - - プロジェクトをダウンロードしない場合は、このトピックの最後の MainWindow.xaml.cs ファイルをレビューできます。 - -## 例のビルド - このトピックの例では、「[非同期タスクまたはタスクの一覧のキャンセル (C#)](../../../../csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md)」で開発したプロジェクトに追加して、タスクのリストをキャンセルします。 この例では、**[キャンセル]** ボタンは明示的に使用していませんが、同じ UI を使用します。 - - この例を自分で 1 つずつビルドするには、"例をダウンロードする" セクションの手順に従います。ただし、**[スタートアップ プロジェクト]** として **CancelAListOfTasks** を選択します。 そのプロジェクトに、このトピックでの変更を追加します。 - - 次の例に示すように、タスクが取り消し済みとマークされるまでの最大時間を指定するには、`CancelAfter` に `startButton_Click` への呼び出しを追加します。 追加部分にはアスタリスクが付いています。 - -```csharp -private async void startButton_Click(object sender, RoutedEventArgs e) -{ - // Instantiate the CancellationTokenSource. - cts = new CancellationTokenSource(); - - resultsTextBox.Clear(); - - try - { - // ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You - // can adjust the time.) - cts.CancelAfter(2500); - - await AccessTheWebAsync(cts.Token); - resultsTextBox.Text += "\r\nDownloads succeeded.\r\n"; - } - catch (OperationCanceledException) - { - resultsTextBox.Text += "\r\nDownloads canceled.\r\n"; - } - catch (Exception) - { - resultsTextBox.Text += "\r\nDownloads failed.\r\n"; - } - - cts = null; -} -``` - - プログラムを複数回実行して、出力がすべての Web サイトの出力を示したり、どの Web サイトの出力も示さなかったり、一部の Web サイトの出力を示したりすることを確認します。 出力例を次に示します。 - -``` -Length of the downloaded string: 35990. - -Length of the downloaded string: 407399. - -Length of the downloaded string: 226091. - -Downloads canceled. -``` - -## コード例全体 - 次のコードは、この例での MainWindow.xaml.cs ファイルのテキスト全体です。 アスタリスクはこの例のために追加された要素を示しています。 - - の参照を追加する必要があることに注意してください。 - - このプロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。 - -```csharp -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; - -// Add a using directive and a reference for System.Net.Http. -using System.Net.Http; - -// Add the following using directive. -using System.Threading; - -namespace CancelAfterTime -{ - public partial class MainWindow : Window - { - // Declare a System.Threading.CancellationTokenSource. - CancellationTokenSource cts; - - public MainWindow() - { - InitializeComponent(); - } - - private async void startButton_Click(object sender, RoutedEventArgs e) - { - // Instantiate the CancellationTokenSource. - cts = new CancellationTokenSource(); - - resultsTextBox.Clear(); - - try - { - // ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You - // can adjust the time.) - cts.CancelAfter(2500); - - await AccessTheWebAsync(cts.Token); - resultsTextBox.Text += "\r\nDownloads succeeded.\r\n"; - } - catch (OperationCanceledException) - { - resultsTextBox.Text += "\r\nDownloads canceled.\r\n"; - } - catch (Exception) - { - resultsTextBox.Text += "\r\nDownloads failed.\r\n"; - } - - cts = null; - } - - // You can still include a Cancel button if you want to. - private void cancelButton_Click(object sender, RoutedEventArgs e) - { - if (cts != null) - { - cts.Cancel(); - } - } - - async Task AccessTheWebAsync(CancellationToken ct) - { - // Declare an HttpClient object. - HttpClient client = new HttpClient(); - - // Make a list of web addresses. - List urlList = SetUpURLList(); - - foreach (var url in urlList) - { - // GetAsync returns a Task. - // Argument ct carries the message if the Cancel button is chosen. - // Note that the Cancel button cancels all remaining downloads. - HttpResponseMessage response = await client.GetAsync(url, ct); - - // Retrieve the website contents from the HttpResponseMessage. - byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); - - resultsTextBox.Text += - String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length); - } - } - - private List SetUpURLList() - { - List urls = new List - { - "http://msdn.microsoft.com", - "http://msdn.microsoft.com/library/windows/apps/br211380.aspx", - "http://msdn.microsoft.com/library/hh290136.aspx", - "http://msdn.microsoft.com/library/ee256749.aspx", - "http://msdn.microsoft.com/library/ms404677.aspx", - "http://msdn.microsoft.com/library/ff730837.aspx" - }; - return urls; - } - } - - // Sample Output: - - // Length of the downloaded string: 35990. - - // Length of the downloaded string: 407399. - - // Length of the downloaded string: 226091. - - // Downloads canceled. -} -``` - -## 参照 - -- [Async および Await を使用した非同期プログラミング (C#)](../../../../csharp/programming-guide/concepts/async/index.md) -- [チュートリアル: async と await を使用した Web へのアクセス (C#)](../../../../csharp/programming-guide/concepts/async/walkthrough-accessing-the-web-by-using-async-and-await.md) -- [非同期タスクまたはタスクの一覧のキャンセル (C#)](../../../../csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md) -- [非同期アプリケーションの微調整 (C#)](../../../../csharp/programming-guide/concepts/async/fine-tuning-your-async-application.md) +> この例を実行するには、コンピューターに Visual Studio 2012 以降および .NET Framework 4.5 以降がインストールされている必要があります。 + +## サンプルをダウンロードする + +完全な Windows Presentation Foundation (WPF) プロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。ダウンロード後、次の手順に従います。 + +1. ダウンロードしたファイルを圧縮解除し、Visual Studio を起動します。 + +2. メニュー バーで、**[ファイル]** > **[開く]** > **[プロジェクト/ソリューション]** を選択します。 + +3. **[プロジェクトを開く]** ダイアログ ボックスで、圧縮解除したサンプル コードを含むフォルダーを開き、AsyncFineTuningCS のソリューション (.sln) ファイルを開きます。 + +4. **ソリューション エクスプローラー**で、**CancelAfterTime** プロジェクトのショートカット メニューを開き、**[スタートアップ プロジェクトに設定]** をクリックします。 + +5. **F5** キーを押してプロジェクトを実行します (デバッグを実行せずにプロジェクトを実行するには、**Ctrl**+**F5** キーを押します)。 + +6. プログラムを複数回実行して、出力がすべての Web サイトの出力を示したり、どの Web サイトの出力も示さなかったり、一部の Web サイトの出力を示したりすることを確認します。 + +プロジェクトをダウンロードしない場合は、このトピックの最後の MainWindow.xaml.cs ファイルをレビューできます。 + +## サンプルをビルドする + +このトピックの例では、「[非同期タスクまたはタスクの一覧のキャンセル (C#)](../../../../csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md)」で開発したプロジェクトに追加して、タスクのリストをキャンセルします。 この例では、**[キャンセル]** ボタンは明示的に使用していませんが、同じ UI を使用します。 + +この例を自分で 1 つずつビルドするには、"例をダウンロードする" セクションの手順に従います。ただし、**[スタートアップ プロジェクト]** として **CancelAListOfTasks** を選択します。 そのプロジェクトに、このトピックでの変更を追加します。 + +次の例に示すように、タスクが取り消し済みとマークされるまでの最大時間を指定するには、`CancelAfter` に `startButton_Click` への呼び出しを追加します。 追加部分にはアスタリスクが付いています。 + +```csharp +private async void startButton_Click(object sender, RoutedEventArgs e) +{ + // Instantiate the CancellationTokenSource. + cts = new CancellationTokenSource(); + + resultsTextBox.Clear(); + + try + { + // ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You + // can adjust the time.) + cts.CancelAfter(2500); + + await AccessTheWebAsync(cts.Token); + resultsTextBox.Text += "\r\nDownloads succeeded.\r\n"; + } + catch (OperationCanceledException) + { + resultsTextBox.Text += "\r\nDownloads canceled.\r\n"; + } + catch (Exception) + { + resultsTextBox.Text += "\r\nDownloads failed.\r\n"; + } + + cts = null; +} +``` + + プログラムを複数回実行して、出力がすべての Web サイトの出力を示したり、どの Web サイトの出力も示さなかったり、一部の Web サイトの出力を示したりすることを確認します。 出力例を次に示します。 + +``` +Length of the downloaded string: 35990. + +Length of the downloaded string: 407399. + +Length of the downloaded string: 226091. + +Downloads canceled. +``` + +## コード例全体 + +次のコードは、この例での MainWindow.xaml.cs ファイルのテキスト全体です。 アスタリスクはこの例のために追加された要素を示しています。 + + の参照を追加する必要があることに注意してください。 + +このプロジェクトは「[Async Sample: Fine Tuning Your Application (非同期のサンプル: アプリケーションの微調整)](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)」からダウンロードできます。 + +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +// Add a using directive and a reference for System.Net.Http. +using System.Net.Http; + +// Add the following using directive. +using System.Threading; + +namespace CancelAfterTime +{ + public partial class MainWindow : Window + { + // Declare a System.Threading.CancellationTokenSource. + CancellationTokenSource cts; + + public MainWindow() + { + InitializeComponent(); + } + + private async void startButton_Click(object sender, RoutedEventArgs e) + { + // Instantiate the CancellationTokenSource. + cts = new CancellationTokenSource(); + + resultsTextBox.Clear(); + + try + { + // ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You + // can adjust the time.) + cts.CancelAfter(2500); + + await AccessTheWebAsync(cts.Token); + resultsTextBox.Text += "\r\nDownloads succeeded.\r\n"; + } + catch (OperationCanceledException) + { + resultsTextBox.Text += "\r\nDownloads canceled.\r\n"; + } + catch (Exception) + { + resultsTextBox.Text += "\r\nDownloads failed.\r\n"; + } + + cts = null; + } + + // You can still include a Cancel button if you want to. + private void cancelButton_Click(object sender, RoutedEventArgs e) + { + if (cts != null) + { + cts.Cancel(); + } + } + + async Task AccessTheWebAsync(CancellationToken ct) + { + // Declare an HttpClient object. + HttpClient client = new HttpClient(); + + // Make a list of web addresses. + List urlList = SetUpURLList(); + + foreach (var url in urlList) + { + // GetAsync returns a Task. + // Argument ct carries the message if the Cancel button is chosen. + // Note that the Cancel button cancels all remaining downloads. + HttpResponseMessage response = await client.GetAsync(url, ct); + + // Retrieve the website contents from the HttpResponseMessage. + byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); + + resultsTextBox.Text += + String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length); + } + } + + private List SetUpURLList() + { + List urls = new List + { + "http://msdn.microsoft.com", + "http://msdn.microsoft.com/library/windows/apps/br211380.aspx", + "http://msdn.microsoft.com/library/hh290136.aspx", + "http://msdn.microsoft.com/library/ee256749.aspx", + "http://msdn.microsoft.com/library/ms404677.aspx", + "http://msdn.microsoft.com/library/ff730837.aspx" + }; + return urls; + } + } + + // Sample Output: + + // Length of the downloaded string: 35990. + + // Length of the downloaded string: 407399. + + // Length of the downloaded string: 226091. + + // Downloads canceled. +} +``` + +## 関連項目 + +- [Async および Await を使用した非同期プログラミング (C#)](../../../../csharp/programming-guide/concepts/async/index.md) +- [チュートリアル: async と await を使用した Web へのアクセス (C#)](../../../../csharp/programming-guide/concepts/async/walkthrough-accessing-the-web-by-using-async-and-await.md) +- [非同期タスクまたはタスクの一覧のキャンセル (C#)](../../../../csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md) +- [非同期アプリケーションの微調整 (C#)](../../../../csharp/programming-guide/concepts/async/fine-tuning-your-async-application.md) - [非同期のサンプル: アプリケーションの微調整](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea) diff --git a/docs/csharp/programming-guide/concepts/async/control-flow-in-async-programs.md b/docs/csharp/programming-guide/concepts/async/control-flow-in-async-programs.md index ff117b74dfa..c9919f61a6b 100644 --- a/docs/csharp/programming-guide/concepts/async/control-flow-in-async-programs.md +++ b/docs/csharp/programming-guide/concepts/async/control-flow-in-async-programs.md @@ -2,386 +2,392 @@ title: 非同期プログラムにおける制御フロー (C#) ms.date: 07/20/2015 ms.assetid: fc92b08b-fe1d-4d07-84ab-5192fafe06bb -ms.openlocfilehash: b05bfbd231745caf9e8b6031ce8e063469d8898b -ms.sourcegitcommit: 2eceb05f1a5bb261291a1f6a91c5153727ac1c19 +ms.openlocfilehash: 49123dde51acaa82a2d8fa7d27fdf27087675034 +ms.sourcegitcommit: ad99773e5e45068ce03b99518008397e1299e0d1 ms.translationtype: HT ms.contentlocale: ja-JP -ms.lasthandoff: 09/04/2018 -ms.locfileid: "43502503" +ms.lasthandoff: 09/22/2018 +ms.locfileid: "46586780" --- # 非同期プログラムにおける制御フロー (C#) -`async` キーワードと `await` キーワードを使用すると、非同期のプログラムの作成と保守をより簡単に行えます。 ただし、プログラムがどのように動作するかを理解しないと、その結果は予想に反するものになる場合があります。 このトピックでは、簡単な非同期プログラムによる制御フローをトレースして、制御があるメソッドから別のメソッドに移るタイミングと、その都度転送される情報について説明します。 - -> [!NOTE] -> `async` キーワードおよび `await` キーワードは、Visual Studio 2012 で導入されました。 - - 一般に、[async (C#)](../../../../csharp/language-reference/keywords/async.md) 修飾子を使用した非同期コードを含むメソッドをマークします。 async 修飾子でマークされたメソッドでは、[await (C#)](../../../../csharp/language-reference/keywords/await.md) 演算子を使用して、呼び出される非同期処理の終了をメソッドが待機する場所を指定できます。 詳細については、「[Async および Await を使用した非同期プログラミング (C#)](../../../../csharp/programming-guide/concepts/async/index.md)」を参照してください。 - - 次の例では、非同期メソッドを使用して、指定した Web サイトのコンテンツを文字列としてダウンロードし、その文字列の長さを表示します。 この例には、次の 2 つのメソッドが含まれています。 - -- `startButton_Click` を呼び出して結果を表示する `AccessTheWebAsync`。 - -- Web サイトのコンテンツを文字列としてダウンロードして、その文字列の長さを返す `AccessTheWebAsync`。 `AccessTheWebAsync` は、非同期 メソッドである を使用してコンテンツをダウンロードします。 - - 番号付き表示行はプログラム全体で重要なポイントを示し、プログラムがどのように実行され、マークされている各ポイントで何が発生するかを理解するために役立ちます。 表示行には「1」から「6」までのラベルが付けられています。 このラベルは、プログラムがこれらのコード行に到達する順序を表します。 - - 次のコードは、プログラムの概要を示します。 - -```csharp -public partial class MainWindow : Window -{ - // . . . - private async void startButton_Click(object sender, RoutedEventArgs e) - { - // ONE - Task getLengthTask = AccessTheWebAsync(); - - // FOUR - int contentLength = await getLengthTask; - - // SIX - resultsTextBox.Text += - String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength); - } - - async Task AccessTheWebAsync() - { - // TWO - HttpClient client = new HttpClient(); - Task getStringTask = - client.GetStringAsync("http://msdn.microsoft.com"); - - // THREE - string urlContents = await getStringTask; - - // FIVE - return urlContents.Length; - } -} -``` - - 「1」から「6」までのそれぞれのラベルの位置は、プログラムの現在の状態に関する情報を表示します。 次の出力が生成されます。 - -``` -ONE: Entering startButton_Click. - Calling AccessTheWebAsync. - -TWO: Entering AccessTheWebAsync. - Calling HttpClient.GetStringAsync. - -THREE: Back in AccessTheWebAsync. - Task getStringTask is started. - About to await getStringTask & return a Task to startButton_Click. - -FOUR: Back in startButton_Click. - Task getLengthTask is started. - About to await getLengthTask -- no caller to return to. - -FIVE: Back in AccessTheWebAsync. - Task getStringTask is complete. - Processing the return statement. - Exiting from AccessTheWebAsync. - -SIX: Back in startButton_Click. - Task getLengthTask is finished. - Result from AccessTheWebAsync is stored in contentLength. - About to display contentLength and exit. - -Length of the downloaded string: 33946. -``` - -## プログラムをセットアップする - このトピックで使用するコードは、MSDN からダウンロードするか、または自分でビルドできます。 - + +`async` キーワードと `await` キーワードを使用すると、非同期のプログラムの作成と保守をより簡単に行えます。 ただし、プログラムがどのように動作するかを理解しないと、その結果は予想に反するものになる場合があります。 このトピックでは、簡単な非同期プログラムによる制御フローをトレースして、制御があるメソッドから別のメソッドに移るタイミングと、その都度転送される情報について説明します。 + +一般に、[async (C#)](../../../../csharp/language-reference/keywords/async.md) 修飾子を使用した非同期コードを含むメソッドをマークします。 async 修飾子でマークされたメソッドでは、[await (C#)](../../../../csharp/language-reference/keywords/await.md) 演算子を使用して、呼び出される非同期処理の終了をメソッドが待機する場所を指定できます。 詳細については、「[Async および Await を使用した非同期プログラミング (C#)](../../../../csharp/programming-guide/concepts/async/index.md)」を参照してください。 + +次の例では、非同期メソッドを使用して、指定した Web サイトのコンテンツを文字列としてダウンロードし、その文字列の長さを表示します。 この例には、次の 2 つのメソッドが含まれています。 + +- `startButton_Click` を呼び出して結果を表示する `AccessTheWebAsync`。 + +- Web サイトのコンテンツを文字列としてダウンロードして、その文字列の長さを返す `AccessTheWebAsync`。 `AccessTheWebAsync` は、非同期 メソッドである を使用してコンテンツをダウンロードします。 + +番号付き表示行はプログラム全体で重要なポイントを示し、プログラムがどのように実行され、マークされている各ポイントで何が発生するかを理解するために役立ちます。 表示行には「1」から「6」までのラベルが付けられています。 このラベルは、プログラムがこれらのコード行に到達する順序を表します。 + +次のコードは、プログラムの概要を示します。 + +```csharp +public partial class MainWindow : Window +{ + // . . . + private async void startButton_Click(object sender, RoutedEventArgs e) + { + // ONE + Task getLengthTask = AccessTheWebAsync(); + + // FOUR + int contentLength = await getLengthTask; + + // SIX + resultsTextBox.Text += + String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength); + } + + async Task AccessTheWebAsync() + { + // TWO + HttpClient client = new HttpClient(); + Task getStringTask = + client.GetStringAsync("http://msdn.microsoft.com"); + + // THREE + string urlContents = await getStringTask; + + // FIVE + return urlContents.Length; + } +} +``` + +「1」から「6」までのそれぞれのラベルの位置は、プログラムの現在の状態に関する情報を表示します。 次の出力が生成されます。 + +```text +ONE: Entering startButton_Click. + Calling AccessTheWebAsync. + +TWO: Entering AccessTheWebAsync. + Calling HttpClient.GetStringAsync. + +THREE: Back in AccessTheWebAsync. + Task getStringTask is started. + About to await getStringTask & return a Task to startButton_Click. + +FOUR: Back in startButton_Click. + Task getLengthTask is started. + About to await getLengthTask -- no caller to return to. + +FIVE: Back in AccessTheWebAsync. + Task getStringTask is complete. + Processing the return statement. + Exiting from AccessTheWebAsync. + +SIX: Back in startButton_Click. + Task getLengthTask is finished. + Result from AccessTheWebAsync is stored in contentLength. + About to display contentLength and exit. + +Length of the downloaded string: 33946. +``` + +## プログラムをセットアップする + +このトピックで使用するコードは、MSDN からダウンロードするか、または自分でビルドできます。 + > [!NOTE] -> この例を実行するには、Visual Studio 2012 以降と .NET Framework 4.5 以降が、コンピューターにインストールされている必要があります。 - -### プログラムをダウンロードする - このトピックのアプリケーションは、「[非同期のサンプル: 非同期プログラムにおける制御フロー](https://code.msdn.microsoft.com/Async-Sample-Control-Flow-5c804fc0)」からダウンロードできます。 次の手順でプログラムを開いて実行します。 - -1. ダウンロードしたファイルを解凍し、Visual Studio を開始します。 - -2. メニュー バーで **[ファイル]**、 **[開く]**、 **[プロジェクト/ソリューション]** の順に選択します。 - -3. 解凍したサンプル コードが含まれるフォルダーに移動し、ソリューション (.sln) ファイルを開き、F5 キーを押してプロジェクトをビルドし、実行します。 - -### プログラムを手動でビルドする - 次の Windows Presentation Foundation (WPF) プロジェクトには、このトピックのコード例が含まれています。 - - このプロジェクトを実行するには、次の手順を実行します。 - -1. Visual Studio を起動します。 - -2. メニュー バーで、 **[ファイル]**、 **[新規作成]**、 **[プロジェクト]** の順にクリックします。 - - **[新しいプロジェクト]** ダイアログ ボックスが表示されます。 - -3. **[インストールされたテンプレート]** ウィンドウで、**[Visual C#]** をクリックし、プロジェクトの種類の一覧で **[WPF アプリケーション]** をクリックします。 - -4. プロジェクトの名前として「`AsyncTracer`」と入力し、**[OK]** をクリックします。 - - **ソリューション エクスプローラー**に新しいプロジェクトが表示されます。 - -5. Visual Studio コード エディターで、 **[MainWindow.xaml]** タブをクリックします。 - - タブが表示されない場合は、**ソリューション エクスプローラー**で MainWindow.xaml のショートカット メニューを開き、**[コードの表示]** を選択します。 - -6. MainWindow.xaml の **XAML** ビューで、コードを次のコードに置き換えます。 - - ```csharp - - -