0
0

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 3 years have passed since last update.

Task.AsyncStateの使い方

Last updated at Posted at 2021-02-12

AsyncState

あまり使い道が思い浮かばなかったが、一応メモ
AsyncStateを使うとTaskの中に埋め込まれたオブジェクトを取得することが出来る。
Taskの値を取得したいならTask.Resultを使う場合がほとんどだと思うけど、いつ使うんだコレ

using System;
using System.Threading;
using System.Threading.Tasks;

class Program {
    static void Main(string[] args) {
        Task task = Task.Factory.StartNew(  x => Calc(  (Data)x),   new Data(){init = 123});

        task.Wait();    
        Data data = task.AsyncState as Data;
        Console.WriteLine(  "init:{0}   id:{1}  rand:{2}",  data.init,  data.id,    data.rand); 
    } 
    public static void Calc(    Data data){
        data.id = Thread.CurrentThread.ManagedThreadId;
        data.rand = new Random().Next(1000);
    }
}
class Data{
    public int init;
    public int id;
    public int rand;
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?