简体   繁体   中英

How to convert thread Code (VB.net to C#)..?

how to convert my VB.net code to C#..? I want to use a looping function with a thread.

  1. VB.Net Code

     For i As Integer = 0 To _port_count Dim worker As New Threading.Thread(AddressOf looping) worker.Start(_list(i)) commThread.Add(worker) Next

public sub looping(Byvar PortList As PortList) 'looping function

  1. C# Code

     for (int i = 0; i <= _port_count; i++) { Thread worker = new Thread(looping); worker.Start(_list[i]); commThread.Add(worker); }

public static void looping (PortList PortList) {}

but C# code didn't work. :(

thanks for your helps.

What's declaration of looping function ?

And some more info ?

Here is an example from Microsoft Docs.

using System;
using System.Threading;

public class Work
{
    public static void Main()
    {
        // Start a thread that calls a parameterized static method.
        Thread newThread = new Thread(Work.DoWork);
        newThread.Start(42);

        // Start a thread that calls a parameterized instance method.
        Work w = new Work();
        newThread = new Thread(w.DoMoreWork);
        newThread.Start("The answer.");
    }

    public static void DoWork(object data)
    {
        Console.WriteLine("Static thread procedure. Data='{0}'",
            data);
    }

    public void DoMoreWork(object data)
    {
        Console.WriteLine("Instance thread procedure. Data='{0}'",
            data);
    }
}
// This example displays output like the following:
//       Static thread procedure. Data='42'
//       Instance thread procedure. Data='The answer.'

link: https://msdn.microsoft.com/en-us/library/1h2f2459(v=vs.110)

Change you looping-method signature to following:

public static void looping (object PortList)

As documentation says, ParameterizedThreadStart passed as Thread constructor parameter has to be object .

The Thread constructor will take either a ThreadStart delegate or a ParameterizedThreadStart delegate. The first has no parameters and the second has one parameter of type object . If you're using a named method then it has to match one of those two signatures, which yours does not. VB will allow you to do the wrong thing and attempt to clean up for you if it can but C# expects you to do the right thing yourself. These days, if you want to call a method whose signature does not match, you can use a Lambda with a matching signature instead, then call your method in that:

Thread worker = new Thread(() => looping(_list[i]));
worker.Start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM