有关 C# 中线程的问题

本文关键字:问题 线程 有关 | 更新日期: 2023-09-27 17:56:32

我目前有一个 Windows 窗体应用程序,我想创建一个新线程并在另一个接受输入的类上运行一个方法。

例如

public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
}
class SMS
{
    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }
    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other codes
    }
}

如何在 C# 中执行此操作?我在网络上看到过许多示例,其中大多数示例在同一个类上运行该方法,没有参数,但没有一个适合我的要求。

有关 C# 中线程的问题

也许后台工作者可以帮助您?
有点难以理解您的目标。

public class Runner
{
    private readonly BackgroundWorker _worker = new BackgroundWorker();
    public Runner()
    {
        _worker.DoWork += WorkerDoWork;
    }
    public void RunMe(int payload)
    {
        _worker.RunWorkerAsync(payload);
    }
    static void WorkerDoWork(object sender, DoWorkEventArgs e)
    {
        var worker = sender as BackgroundWorker;
        while (true)
        {
            if (worker.CancellationPending)
            {
                e.Cancel = true;
                break;
            }
            // Work
            System.Threading.Thread.Sleep((int)e.Argument);
        }
    }
}

我不是多线程方面的专家,但据我所知,您只能在接受对象参数并返回 void 的方法上启动线程。因此,为了解决您的问题(如果有更好的方法,请不要击落我!我会做这样的事情

public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
    SMS sms = new SMS();
    Thread t = new Thread(sms.SMSListenerUntyped);
    t.Start(serialInput);
}
class SMS
{
    public void SMSListenerUntyped(object serial1) {
        if (serial1 is SerialPort) //Check if the parameter is correctly typed.
             this.SMSListener(serial1 as SerialPort);
        else
           throw new ArgumentException();
    }
    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }
    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other code.
    }

直接使用ThreadPool和匿名方法,允许你访问周围的当地人怎么样?

    public void OnButtonClick(object sender, EventArgs e)
    {
        SerialPort serialInput = this.SerialInput;
        System.Threading.ThreadPool.QueueUserWorkItem(delegate
        {
            SmsListener listener = new SmsListener(serialInput);
        });
    }