Skip to Content
Concurrency in C# Cookbook、第 2 版
book

Concurrency in C# Cookbook、第 2 版

by Stephen Cleary
May 2025
Intermediate to advanced
254 pages
3h 28m
Japanese
O'Reilly Media, Inc.
Content preview from Concurrency in C# Cookbook、第 2 版

第14章. シナリオ

この作品はAIを使って翻訳されている。ご意見、ご感想をお待ちしている:translation-feedback@oreilly.com

この章では、並行プログラムを書くときによくあるシナリオに対処するための、さまざまな型とテクニックを紹介する。この種のシナリオは、別の本一冊を埋め尽くすことができるので、私が最も有用だと発見したものをいくつか選んだ。

14.1 共有リソースの初期化

問題

コードの複数の部分で共有されるリソースがある。このリソースは、最初にアクセスされたときに初期化される必要がある。

解決策

.NETフレームワークには、この目的に特化した型がある:Lazy<T> 。インスタンスの初期化に使用されるファクトリー・デリゲートで、Lazy<T> 型のインスタンスを構築する。インスタンスは、Value プロパティで利用できるようになる。次のコードは、Lazy<T> 型を示している:

static int _simpleValue;
static readonly Lazy<int> MySharedInteger = new Lazy<int>(() => _simpleValue++);

void UseSharedInteger()
{
  int sharedValue = MySharedInteger.Value;
}

いくつのスレッドが同時にUseSharedInteger を呼び出しても、ファクトリー委譲は一度しか実行されず、すべてのスレッドが同じインスタンスを待つ。一度作成されると、インスタンスはキャッシュされ、今後Value プロパティにアクセスすると、すべて同じインスタンスが返される(前述の例では、MySharedInteger.Value は常に0 になる)。

初期化に非同期作業が必要な場合も、よく似たアプローチが使える。この場合、Lazy<Task<T>>

static int _simpleValue;
static readonly Lazy<Task<int>> MySharedAsyncInteger =
    new Lazy<Task<int>>(async () =>
    {
      await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
      return _simpleValue++;
    });

async Task GetSharedIntegerAsync()
{
  int sharedValue = await MySharedAsyncInteger.Value;
}

この例では、委譲はTask<int> 、つまり非同期に決定された整数値を返す。コードのいくつの部分が同時にValue を呼び出そうとも、Task<int> は一度だけ作成され、すべての呼び出し元に返される。その後、各呼び出し元は、await にタスクを渡すことで、タスクが完了するまで(非同期に)待機するオプションがある。

先行のコードは許容できるパターンだが、さらに考慮すべき点がいくつかある。一つは、非同期委譲は、Value を呼び出すどのスレッドでも実行することができ、その委譲はそのコンテキスト内で実行される。もしValue (例えば、UIスレッドとスレッドプールスレッド、または2つの異なるASP.NETリクエストスレッド)を呼び出す可能性のある異なるスレッドタイプがある場合、常にスレッドプールスレッド上で非同期委譲を実行する方がよいかもしれない。この ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Async in C# 5.0

Async in C# 5.0

Alex Davies

Publisher Resources

ISBN: 9798341650060