Returning a value from thread?

前端 未结 17 2532
不思量自难忘°
不思量自难忘° 2020-11-27 09:45

How do I return a value from a thread?

17条回答
  •  时光说笑
    2020-11-27 10:43

    It depends on how do you want to create the thread and available .NET version:

    .NET 2.0+:

    A) You can create the Thread object directly. In this case you could use "closure" - declare variable and capture it using lambda-expression:

    object result = null;
    Thread thread = new System.Threading.Thread(() => { 
        //Some work...
        result = 42; });
    thread.Start();
    thread.Join();
    Console.WriteLine(result);
    

    B) You can use delegates and IAsyncResult and return value from EndInvoke() method:

    delegate object MyFunc();
    ...
    MyFunc x = new MyFunc(() => { 
        //Some work...
        return 42; });
    IAsyncResult asyncResult = x.BeginInvoke(null, null);
    object result = x.EndInvoke(asyncResult);
    

    C) You can use BackgroundWorker class. In this case you could use captured variable (like with Thread object) or handle RunWorkerCompleted event:

    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (s, e) => {
        //Some work...
        e.Result = 42;
    };
    worker.RunWorkerCompleted += (s, e) => {
        //e.Result "returned" from thread
        Console.WriteLine(e.Result);
    };
    worker.RunWorkerAsync();
    

    .NET 4.0+:

    Starting with .NET 4.0 you could use Task Parallel Library and Task class to start your threads. Generic class Task allows you to get return value from Result property:

    //Main thread will be blocked until task thread finishes
    //(because of obtaining the value of the Result property)
    int result = Task.Factory.StartNew(() => {
        //Some work...
        return 42;}).Result;
    

    .NET 4.5+:

    Starting with .NET 4.5 you could also use async/await keywords to return value from task directly instead of obtaining Result property:

    int result = await Task.Run(() => {
        //Some work...
        return 42; });
    

    Note: method, which contains the code above shoud be marked with asynckeyword.

    For many reasons using of Task Parallel Library is preferable way of working with threads.

提交回复
热议问题