how to convert my VB.net code to C#..?
I want to use a looping function with a thread.
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
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.
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();
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.
Related
I have the method that takes an argument from external dll through a delegate pointer:
public delegate void NotificationsCallbackDelegate(CinectorNotification message);
NotificationsCallbackDelegate notificationsCallbackDeleg;
IntPtr notificationsCallbackPointer;
notificationsCallbackDeleg = NotificationsCallback;
notificationsCallbackPointer = Marshal.GetFunctionPointerForDelegate(notificationsCallbackDeleg);
instance.SetNotificationsCallback(notificationsCallbackPointer);
private void NotificationsCallback(CinectorNotification notif)
{
Log.AppendText("[" + notif.timestamp + "] " + notif.type + ": " + notif.message + Environment.NewLine);
}
So, input argument 'message' is something that can be passed by dll at any time during the application flow, whenever the external engine generates some log. It is like an event.
I use the following code to put a method on a new thread:
private void startNotifications()
{
Thread NotificationsThread = new Thread(new ThreadStart(NotificationsCallback));
NotificationsThread.IsBackground = true;
NotificationsThread.Start();
}
However, the method NotificationsCallback(CinectorNotification notif) takes in an argument and therefore doesn't match the delegate for ThreadStart. So how would I put a method like this on a different thread?
You can use Task.Run and supply it a lambda where you call NotificationsCallback with whatever arguments you need For example:
private void startNotifications()
{
Task.Run(() => NotificationsCallback(arg1, arg2) );
}
This will result in NotificationsCallback being run on on a ThreadPool thread.
For more information on Task.Run, see: https://msdn.microsoft.com/en-us/library/hh195051(v=vs.110).aspx
You code would work if there is a method passed in the parameter is parameterless.
If you want a parametrised thread, you should use another overload of the Thread constructor which will take ParameterizedThreadStart.
Start method on the thread is then called with an argument which is passed on to the thread method like this:
Thread thread = new Thread(WorkerMethod);
thread.Start(35); //for example 35
void WorkerMethod(object parameter)
{
int? intParameter = parameter as int?; //for example
if (intParameter.HasValue)
{
//do stuff
}
}
You can also use Task, which is a more modern approach to multi-threading.
Task.Factory.StartNew(() => WorkerMethod(35)); //for example 35
Or Task.Run in .NET 4.5 and newer. In task one can pass as many paramaters as wanted (without creating a container for them) and also the parameters can be strongly typed... not just object.
Instead of using ThreadStart you could use ParameterizedThreadStart and pass the required parameters in Thread.Start.
I need to know how to send data over my threads, I have this code.
new Thread(BattleArena.ArenaGame(12)).Start();
And over BattleArena class I have
public static void ArenaGame(int test)
{
while (true)
{
Console.WriteLine(test);
Thread.Sleep(400);
}
}
But that is not a valid way...
Right now you are "sending" the result of a method call. (Not even compilable). You want to send/execute a function:
new Thread(() => BattleArena.ArenaGame(12)).Start();
Don't use parameterized threads, they are obsolete thanks to lambdas.
To clarify: a thread is not a way to send data. It is a way to execute a function. The the function has to contain the data.
You need to use parameterised threads. Like
ThreadStart start = () => { BattleArena.ArenaGame(12); };
Thread t = new Thread(start);
t.Start();
Or
Thread newThread = new Thread(BattleArena.ArenaGame);
newThread.Start(12);
then change this method as it only takes object as parameter as ThreadStart is not a generic delegate
public static void ArenaGame(object value)
{
int test = (int)value;
while (true)
{
Console.WriteLine(test);
Thread.Sleep(400);
}
}
you should use Parameterized ThreadStart
How can I pass a Method2 to thread as shown in below if i write code as shown in below it shows an error Error
The best overloaded method match for
'System.Threading.Thread.Thread(System.Threading.ThreadStart)' has
some invalid arguments
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main Thread : ");
Thread obj = new Thread(Method2);
obj.Start();
Console.ReadLine();
}
private static int Method2(int a)
{
return a;
}
}
When i use the following code it works
Thread obj = new Thread(() => Method2(1));
But why it's not working when i pass delegate object
delegate int del(int i);
del d = Method2;
Thread obj = new Thread(d);
What is the difference between above 2 , in 1st case i used Lambda expression in second case directly passed delegate object is there any thing else?
The Thread constuctor takes two types of delegates, ThreadStart and ParameterizedThreadStart. To see what type of method these delegates accept you can create it and the constructor will show you, so for example,
var parameterMethod = new ParameterizedThreadStart(...
If you type the above you will see the delegate takes a function with one object as the parameter and returns void.
void (object) target
This is why your Method that takes an int will not work because the signature does not match the delegate target signature. When you wrap it in a lambada, you are actually passing in a method that takes no parameters and returns void, so the Method2 signature is not even looked at. Wrapping method calls with a lambada like this can be very useful for getting the signature to match.
delegate void del(object obj);
del d = () => Method2(1);
Thread obj = new Thread(d);
There is an infinite number of possible method signatures so Threads and Tasks keep it simple and say if you want to pass something, pass a single object. Since all types derive from object, this lets you pass in anything you want, then cast it later.
Try this:
Thread obj = new Thread(() => Method2(some_int_value));
In general I get C#'s lambda syntax. However the anonymous thread syntax isn't completely clear to me. Can someone explain what a thread creation like this is actually doing? Please be as detailed as possible, I'd love to have a sort of step-by-step on the magic that makes this work.
(new Thread(() => {
DoLongRunningWork();
MessageBox.Show("Long Running Work Finished!");
})).Start();
The part that I really don't understand is the Thread(() => ...
When I use this syntax it seems like I remove a lot of the limits of a traditional ThreadStart such as having to invoke on a method that has no parameters.
Thanks for your help!
() => ... just means that the lambda expression takes no parameters. Your example is equivalent to the following:
void worker()
{
DoLongRunningWork();
MessageBox.Show("Long Running Work Finished!");
}
// ...
new Thread(worker).Start();
The { ... } in the lambda let you use multiple statements in the lambda body, where ordinarily you'd only be allowed an expression.
This:
() => 1 + 2
Is equivalent to:
() => { return (1 + 2); }
This is anonymous way to create a thread in C# which just start the thread (because you are using Start();)
Following 2 ways are equivalent. If you need Thread variable to do something (for example block the calling thread by calling thread0.join()), then you use the 2nd one.
new Thread(() =>
{
Console.WriteLine("Anonymous Thread job goes here...");
}).Start();
var thread0= new Thread(() =>
{
Console.WriteLine("Named Thread job goes here...");
});
thread0.Start();
Now the Thread method part. If you see the Thread declaration we have the following (I omitted 3 others).
public Thread(ThreadStart start);
Thread takes a delegate as a parameter. Delegate is reference to a method. So Thread takes a parameter which is a delegate. ThreadStart is declared like this.
public delegate void ThreadStart();
It means you can pass any method to Thread which return void and doesn't take any parameters. So following examples are equivalent.
ThreadStart del = new ThreadStart(ThreadMethod);
var thread3 = new Thread(del);
thread3.Start();
ThreadStart del2 = ThreadMethod;
var thread4 = new Thread(del2);
thread4.Start();
var thread5 = new Thread(ThreadMethod);
thread5.Start();
//This must be separate method
public static void ThreadMethod()
{
Console.WriteLine("ThreadMethod doing important job...");
}
Now we think that ThreadMethod method is doing little work we can make it to local and anonymous. So we don't need the ThreadMethod method at all.
new Thread( delegate ()
{
Console.WriteLine("Anonymous method Thread job goes here...");
}).Start();
You see after delegate to last curly braces is equivalent to our ThreadMethod(). You can further shorten the previous code by introducing Lambda statement (See MSDN). This is just you are using and see how it has been ended up like the following.
new Thread( () =>
{
Console.WriteLine("Lambda statements for thread goes here...");
}).Start();
As there was some answers before I started, I will just write about how additional parameters make their way into lambda.
In short this thing called closure. Lets dissect your example with new Thread(() => _Transaction_Finalize_Worker(transId, machine, info, newConfigPath)).Start(); into pieces.
For closure there's a difference between class' fields and local variables. Thus let's assume that transId is class field (thus accessible through this.transId) and others are just local variables.
Behind the scenes if lambda used in a class compiler creates nested class with unspeakable name, lets name it X for simplicity, and puts all local variables there. Also it writes lambda there, so it becomes normal method. Then compiler rewrites your method so that it creates X at some point and replaces access to machine, info and newConfigPath with x.machine, x.info and x.newConfigPath respectively. Also X receives reference to this, so lambda-method could access transId via parentRef.transId.
Well, it is extremely simplified but near to reality.
UPD:
class A
{
private int b;
private int Call(int m, int n)
{
return m + n;
}
private void Method()
{
int a = 5;
a += 5;
Func<int> lambda = () => Call(a, b);
Console.WriteLine(lambda());
}
#region compiler rewrites Method to RewrittenMethod and adds nested class X
private class X
{
private readonly A _parentRef;
public int a;
public X(A parentRef)
{
_parentRef = parentRef;
}
public int Lambda()
{
return _parentRef.Call(a, _parentRef.b);
}
}
private void RewrittenMethod()
{
X x = new X(this);
x.a += 5;
Console.WriteLine(x.Lambda());
}
#endregion
}
I've been trying to pass an object to my main thread process but it seems it will not work in the way I thought it would.
First I create the Thread:
Thread thrUDP;
Then I create the object I will use to store the data I need:
UDPData udpData;
Now I Initialize the object withthe correct data, Set up the new thread and start it with the object passed into the Start() method:
udpData = new UDPData("224.5.6.7", "5000", "0", "2");
thrUDP = new Thread(new ParameterizedThreadStart(SendStatus));
thrUDP.Start(udpData);
This is the method I wish to start:
private void SendStatus(UDPData data)
{
}
I remember using Threads a while back and I'm sure they weren't so difficult to pass data to, am I doing this the wrong way or am I just missing a piece of code?
Thanks!
The ParameterizedThreadStart delegate is declared as:
public delegate void ParameterizedThreadStart(object obj);
Clearly, this delegate isn't compatible with your method's signature, and there isn't a direct way to get a System.Threading.Thread to work with an arbitrary delegate-type.
One of your options would be to use a compatible signature for the method, and cast as appropriate:
private void SendStatus(object obj)
{
UDPData data = (UDPData)obj;
...
}
The other option would be to punt the problem to the C# compiler, creating a closure. For example:
new Thread(() => SendStatus(udpData)).Start();
Do note that this uses the ThreadStart delegate instead. Additionally, you should be careful with subsequently modifying the udpData local, since it is captured.
Alternatively, if you don't mind using the thread-pool instead of spawning your own thread, you could use asynchronous delegates. For example:
Action<UDPData> action = SendStatus;
action.BeginInvoke(udpData, action.EndInvoke, null);
private void SendStatus(object data)
{
UDPData myData = (UDPData) data;
}