How to Retrieve Data from a Thread Function in C#

DevNotes
0

using System;
using System.Threading;

// Tạo delegate 
public delegate void ResultCallbackDelegate(int Results);

// Tạo Helper class, lớp tiện ích giúp thực thi các chức năng 
class NumberHelper
{
    // Tạo hai biến tham chiếu giữ giá trị number và thực thể delegate
    int _number;
    ResultCallbackDelegate _resultCallBackDelegate;

    // Truyền giá trị cho hai biến qua constructor
    public NumberHelper(int number, ResultCallbackDelegate resultCallBackDelegate)
    {
        _number = number;
        _resultCallBackDelegate = resultCallBackDelegate;
    }

    // Hàm void dùng cho chạy threadStart
    public void CalculateSum()
    {
        // Tính toán biến Result
        int Result = 0;
        for (int i = 0; i <= _number; i++)
        {
            Result += i;
        }

        // Truyền biến result, thực thi deledate 
        _resultCallBackDelegate?.Invoke(Result);
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Khởi tạo giá trị cho number và resultCallBackDelegate
        int number = 10;
        var resultCallBackDelegate = new ResultCallbackDelegate(ResultCallbackMethod);
        
        // tạo đối tượng obj bằng constructor truyền hai ham số
        var obj = new NumberHelper(number, resultCallBackDelegate);

        // dùng ThreadStart để chạy hàm void
        var T1 = new Thread(new ThreadStart(obj.CalculateSum));
        T1.Start();
        Console.Read();
    }

    // hàm delegate
    private static void ResultCallbackMethod(int Results)
    {
        Console.WriteLine("The result is " + Results);
    }
}

CallBack Function là gì ?
Callback function như là một con trỏ hàm, là một tham sốt truyền của một hàm khác

Post a Comment

0 Comments
Post a Comment (0)
To Top