1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C# 非同期処理を引数で渡す方法

Posted at

Task<>,async,awaitをどこに付ければ良いのか、、慣れないと書き方に戸惑うので備忘…

非同期処理を引数とするメソッドを作成する

ある処理を外部から引数で渡したい場合、下記のようにActionFunc<T>を使用するが、

同期処理を引数とするメソッドの定義

TResult Sample<TResult>(Func<int, TResult> func)
{
  //todo 前処理
  var result = func(100);
  //todo 後処理
  return result;
}

この引数funcを非同期にしたい場合は下記のようにする。

非同期処理を引数とするメソッドの定義

async Task<TResult> SampleAsync<TResult>(Func<int, Task<TResult>> func)
{
  //todo 前処理
  var result = await func(100);
  //todo 後処理
  return result;
}

非同期処理を引数とするメソッドを呼び出す

async Task<int> CallAsync()
{
  return await SampleAsync(async num =>
  {
    return await Task.FromResult(num * 2); //todo 非同期処理
  });
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?