.NET Threading - Quick question - c#

What should I put instead of the "SomeType" in the below function?
Delegate seems to be wrong here..
public static void StartThread(SomeType target)
{
ThreadStart tstart = new ThreadStart(target);
Thread thread = new Thread(tstart);
thread.Start();
}
EDIT: I'm not looking for alternative ways to write this.

Try the System.Action type.
Here my test code:
static void Main(string[] args)
{
StartThread(() => Console.WriteLine("Hello World!"));
Console.ReadKey();
}
public static void StartThread(Action target)
{
ThreadStart tstart = new ThreadStart(target);
Thread thread = new Thread(tstart);
thread.Start();
}

You should have the ThreadStart as the argument instead of trying to initialize it within the method.

I think there will be no Sometype, as you are calling some function that will be threaded. Isn't so?
Like
Thread t = new Thread(new ThreadStart(function_name_here));
t.start();
and
void function_name_here()
{
Blah blah
}
FYI there is no return type but VOID.

Replace SomeType with System.Threading.ThreadStart or System.Threading.ParameterizedThreadStart.

Related

Can we invoke method outside the thread block by any technique in C#? so that we can use same thread method to invoke other methods as well.?

e.g.
Here in this example, if I want to start thread on method M1 this way,
Purpose is I need to call M2, M3 on same thread method to avoid repeated code.
Is this possible in C#?
static void Main()
{
if(StartThread() => M1()) //I want to invoke Method M1 from here like this
{
return;
}
}
private void StartThread()
{
var t = new Thread(() => M1()); //I dont want to invoke Method M1 from here
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
}
private static void M1()
{
throw new NotImplementedException();
}
Just use a delegate (e.g. an Action) and pass it to StartThread:
static void Main()
{
if(StartThread(() => M1()))
return;
}
private void StartThread(Action a)
{
var t = new Thread(() => a());
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
}
private static void M1()
{
throw new NotImplementedException();
}

Multi threading; pass object to another object

I need to pass an object to another object. I know I have to pass c to t1. How do I do this
Thread t = new Thread(t1);
t.Start();
private static void t1(Class1 c)
{
while (c.process_done == false)
{
Console.Write(".");
Thread.Sleep(1000);
}
}
Ok guys, everybody is missing the point the object is being used outside the thread as well. This way, it must be synchronized to avoid cross-thread exceptions.
So, the solution would be something like this:
//This is your MAIN thread
Thread t = new Thread(new ParameterizedThreadStart(t1));
t.Start(new Class1());
//...
lock(c)
{
c.magic_is_done = true;
}
//...
public static void t1(Class1 c)
{
//this is your SECOND thread
bool stop = false;
do
{
Console.Write(".");
Thread.Sleep(1000);
lock(c)
{
stop = c.magic_is_done;
}
while(!stop)
}
}
Hope this helps.
Regards
You could simply do:
Thread t = new Thread(new ParameterizedThreadStart(t1));
t.Start(new Class1());
public static void t1(object c)
{
Class1 class1 = (Class1)c;
...
}
MSDN: ParameterizedThreadStart Delegate
Or even better:
Thread thread = new Thread(() => t1(new Class1()));
public static void t1(Class1 c)
{
// no need to cast the object here.
...
}
This approach permits multiple arguments and does not require you to cast the object to the desired class/struct.
private static void DoSomething()
{
Class1 whatYouWant = new Class1();
Thread thread = new Thread(DoSomethingAsync);
thread.Start(whatYouWant);
}
private static void DoSomethingAsync(object parameter)
{
Class1 whatYouWant = parameter as Class1;
}

How to create a thread and parse a parameter in C# 2.0

I have an method Process(Progressbar) in class Blacklist
i tried to use this :
Thread thread = new Thread(() => Blacklist.Process(pgImportProcess));
it occurs an error
C# 3.0 language Feature
So how can i create a thread and parse progressbar as a parameter?
Thank in advance
have you tried:
void Invoker(){
ParameterizedThreadStart pts = Start;
Thread thread = new Thread(pts);
thread.Start(new object());
}
public void Start(object o)
{
//do stuff
}
You can't access a UI object from a different thread than it was created on. Every Control has an Invoke method that will execute a delegate on the UI thread. For example if you need to update your progress bars progress:
progressBar.Invoke(new Action() { () => progressBar.Value = updateValue; });
So you just need to use the Thread constructor that takes a ParameterizedThreadStart delegate.
Thread thread = new Thread(StartProcess);
thread.Start(pgImportProcess);
...
private static void StartProcess(object progressBar) {
Blacklist.Process((ProgressBar)progressBar);
}
Can you create a class to passing your parameter like
public class Sample
{
object _value;
public Sample(object value)
{
this._value = value;
}
public void Do()
{
// dosomething
// Invoke the Process(value)
}
}
And then
Sample p = new Sample("your parameter : Progressbar");
new Thread(new ThreadStart(p.Do)).Start();

Sending Parameters to the Function called by a thread in C#?

Sending Parameters to the Function called by a thread in C#,
this is my code:
myThread = new Thread(new ThreadStart(myfunc));
myThread.Start(i);
public void myfunc(int i)
{
...
}
I get error:
No overload for 'installDrivers' matches delegate
'system.Threading.ThredStart'
You can use a ParameterizedThreadStart.
Thread myThread = new Thread(new ParameterizedThreadStart(myfunc));
myThread.Start(i);
And your function
public void myfunc(object i)
{
int myInt = Convert.ToInt32(i);
}
Another option, utilizing lambdas makes it easy to call functions with any number of parameters, it also avoids the rather nasty conversion from object in the one parameter case:
int paramA = 1;
string paramB = "foo";
var myThread = new Thread(() => SomeFunc(paramA, paramB));
myThread.Start();
public void SomeFunc(int paramA, string paramB)
{
// Do something...
}
use this:
myThread = new Thread(new ParameterizedThreadStart(myfunc));
myThread.Start(i);
public void myfunc(object i) {... }
it might be usefull for your issue
Unless you are using C# < 2.0, you don't need to create a delegate. You can let the compiler implicitly create it for you.
myThread = new Thread(myfunc);
myThread.Start(i);
public void myfunc(object i)
{
int i2 = (int)i; // if i is an int
}
but note that the Thread constructor accepts only two types of delegates: one that is parameterless (ThreadStart) and one that accepts an object parameter (ParameterizedThreadStart). So here we are using the second one.

C#: Can't I use an anonymous delegate in ThreadStart?

Can't I have an anonymous delegate declaration, something similar to the following:
ThreadStart starter = delegate() { go(); };
...
static void go()
{
Console.WriteLine("Nice Work");
}
// (or)
ThreadStart starter=delegate() { Console.WriteLine("Hello");}
You can skip the ThreadStart. This should work.
Thread t = new Thread(() =>
{
Console.WriteLine("Hello!");
});
What error do you get? Missing semicolon? This compiles for me.
static void go()
{
Console.WriteLine("Nice Work");
}
public void Run()
{
ThreadStart starter1 = delegate() { go(); };
ThreadStart starter2 = delegate() { Console.WriteLine("Hello");};
ThreadStart starter3 = () => Console.WriteLine("Hello");
}
Yes, you can. Whats the actual question?
By the way, you're missing a semicolon at the end of your second example:
ThreadStart starter=delegate() { Console.WriteLine("Hello");}
should be:
ThreadStart starter = delegate { Console.WriteLine("Hello"); };
Though the spacing I added is personal choice.

Categories

Resources