How to pass parameters to ThreadStart method in Thread? - c#

How to pass parameters to Thread.ThreadStart() method in C#?
Suppose I have method called 'download'
public void download(string filename)
{
// download code
}
Now I have created one thread in the main method:
Thread thread = new Thread(new ThreadStart(download(filename));
error method type expected.
How can I pass parameters to ThreadStart with target method with parameters?

The simplest is just
string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();
The advantage(s) of this (over ParameterizedThreadStart) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object all the time.

Look at this example:
public void RunWorker()
{
Thread newThread = new Thread(WorkerMethod);
newThread.Start(new Parameter());
}
public void WorkerMethod(object parameterObj)
{
var parameter = (Parameter)parameterObj;
// do your job!
}
You are first creating a thread by passing delegate to worker method and then starts it with a Thread.Start method which takes your object as parameter.
So in your case you should use it like this:
Thread thread = new Thread(download);
thread.Start(filename);
But your 'download' method still needs to take object, not string as a parameter. You can cast it to string in your method body.

You want to use the ParameterizedThreadStart delegate for thread methods that take parameters. (Or none at all actually, and let the Thread constructor infer.)
Example usage:
var thread = new Thread(new ParameterizedThreadStart(download));
//var thread = new Thread(download); // equivalent
thread.Start(filename)

You could also delegate like so...
ThreadStart ts = delegate
{
bool moreWork = DoWork("param1", "param2", "param3");
if (moreWork)
{
DoMoreWork("param1", "param2");
}
};
new Thread(ts).Start();

In Additional
Thread thread = new Thread(delegate() { download(i); });
thread.Start();

I would recommend you to have another class called File.
public class File
{
private string filename;
public File(string filename)
{
this.filename= filename;
}
public void download()
{
// download code using filename
}
}
And in your thread creation code, you instantiate a new file:
string filename = "my_file_name";
myFile = new File(filename);
ThreadStart threadDelegate = new ThreadStart(myFile.download);
Thread newThread = new Thread(threadDelegate);

You can encapsulate the thread function(download) and the needed parameter(s)(filename) in a class and use the ThreadStart delegate to execute the thread function.
public class Download
{
string _filename;
Download(string filename)
{
_filename = filename;
}
public void download(string filename)
{
//download code
}
}
Download = new Download(filename);
Thread thread = new Thread(new ThreadStart(Download.download);

How about this: (or is it ok to use like this?)
var test = "Hello";
new Thread(new ThreadStart(() =>
{
try
{
//Staff to do
Console.WriteLine(test);
}
catch (Exception ex)
{
throw;
}
})).Start();

According to your question...
How to pass parameters to Thread.ThreadStart() method in C#?
...and the error you encountered, you would have to correct your code from
Thread thread = new Thread(new ThreadStart(download(filename));
to
Thread thread = new Thread(new ThreadStart(download));
thread.Start(filename);
However, the question is more complex as it seems at first.
The Thread class currently (4.7.2) provides several constructors and a Start method with overloads.
These relevant constructors for this question are:
public Thread(ThreadStart start);
and
public Thread(ParameterizedThreadStart start);
which either take a ThreadStart delegate or a ParameterizedThreadStart delegate.
The corresponding delegates look like this:
public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(object obj);
So as can be seen, the correct constructor to use seems to be the one taking a ParameterizedThreadStart delegate so that some method conform to the specified signature of the delegate can be started by the thread.
A simple example for instanciating the Thread class would be
Thread thread = new Thread(new ParameterizedThreadStart(Work));
or just
Thread thread = new Thread(Work);
The signature of the corresponding method (called Work in this example) looks like this:
private void Work(object data)
{
...
}
What is left is to start the thread. This is done by using either
public void Start();
or
public void Start(object parameter);
While Start() would start the thread and pass null as data to the method, Start(...) can be used to pass anything into the Work method of the thread.
There is however one big problem with this approach:
Everything passed into the Work method is cast into an object. That means within the Work method it has to be cast to the original type again like in the following example:
public static void Main(string[] args)
{
Thread thread = new Thread(Work);
thread.Start("I've got some text");
Console.ReadLine();
}
private static void Work(object data)
{
string message = (string)data; // Wow, this is ugly
Console.WriteLine($"I, the thread write: {message}");
}
Casting is something you typically do not want to do.
What if someone passes something else which is not a string? As this seems not possible at first (because It is my method, I know what I do or The method is private, how should someone ever be able to pass anything to it?) you may possibly end up with exactly that case for various reasons. As some cases may not be a problem, others are. In such cases you will probably end up with an InvalidCastException which you probably will not notice because it simply terminates the thread.
As a solution you would expect to get a generic ParameterizedThreadStart delegate like ParameterizedThreadStart<T> where T would be the type of data you want to pass into the Work method. Unfortunately something like this does not exist (yet?).
There is however a suggested solution to this issue. It involves creating a class which contains both, the data to be passed to the thread as well as the method that represents the worker method like this:
public class ThreadWithState
{
private string message;
public ThreadWithState(string message)
{
this.message = message;
}
public void Work()
{
Console.WriteLine($"I, the thread write: {this.message}");
}
}
With this approach you would start the thread like this:
ThreadWithState tws = new ThreadWithState("I've got some text");
Thread thread = new Thread(tws.Work);
thread.Start();
So in this way you simply avoid casting around and have a typesafe way of providing data to a thread ;-)

here is the perfect way...
private void func_trd(String sender)
{
try
{
imgh.LoadImages_R_Randomiz(this, "01", groupBox, randomizerB.Value); // normal code
ThreadStart ts = delegate
{
ExecuteInForeground(sender);
};
Thread nt = new Thread(ts);
nt.IsBackground = true;
nt.Start();
}
catch (Exception)
{
}
}
private void ExecuteInForeground(string name)
{
//whatever ur function
MessageBox.Show(name);
}

Related

Getting information back to the main thread from the called thread?

I have a "string" and a "StreamReader" in the main thread. I want to pass these to a thread which will read the streamreader into the string. I want that string to be changed in the main thread. My question is how do I do this?
Additional info: I have specific reasons as to why I want to thread this so please just stick to the specs. Also, I cannot use TPL because I cannot get framework 4.0... Again for specific reasons.
So you make a class with a string and a StreamReader property. You pass in an instance of that class to your other thread using ParameterizedThreadStart. You have that other thread fill that buttercup up by writing to the string property on that instance of your class.
When the thread is done, your string property on the instance of your class will be filled up. Yay.
So something like
class Foo {
public string Bar { get; set; }
}
Then:
Foo foo = new Foo();
var thread = new Thread(o => { Foo f = (Foo)o; f.Bar = "FillMeUpButterCup"; });
thread.Start(foo);
thread.Join();
Console.WriteLine(foo);
Wow!
I left off the StreamReader but now you get the point.
When creating the thread you have ParameterizedThreadStart delegate and a parameter that you could pass there. Just create a class with two properties - string and StreamReader (and possibly whatever else you want to pass there) and pass instance of the class into thread starting method.
public class ThreadStartParam
{
public string Str { get; set; }
public StreamReader StreamReader { get; set; }
}
class Program
{
static void Main(string[] args)
{
var t = new Thread(YourMethod);
var param = new ThreadStartParam();
param.Str = "abc";
param.StreamReader = new StreamReader();
t.Start(param);
}
static void YourMethod(object param)
{
var p = (ThreadStartParam) param;
// whatever
}
}
I wrote a blog post about this sometime last year and I think it'll cover how to properly communicate to a thread and back from a thread. Basically create an object to pass to and from the thread and you can pass to the thread using a ParameterizedThreadStart and you can pass back by having a delegate to invoke.
http://coreyogburn.com/post/Threads-Doing-Them-Right-wGUI.aspx
More specifically in your example of the main thread realizing the changed String that you pass to the thread, I would recommend that on thread completion, you call a method that passes the string value back and re-sets the original string's value. This will prevent the thread from adding to the string while the main thread might try to read it.

How do I get from C# thread to the object which member function was the parameter to that thread?

In C# threads are created by passing a member function:
class SomeClass {
public void ThreadFunction() {Thread.Sleep( Infinite ); }
};
SomeClass myObject = new SomeClass();
Thread thread = new Thread( myObject.ThreadFunction );
thread.Start();
Here ThreadFunction() is not static, so I guess the object reference is passed to Thread constructor.
How can code inside ThreadFunction() get to myObject? Do I just use this reference for that?
Like this:
class SomeClass {
public void ThreadFunction(Object obj)
{
SomeClass myObject = (SomeClass)obj;
Thread.Sleep( Infinite );
}
};
SomeClass myObject = new SomeClass();
Thread thread = new Thread(new ParameterizedThreadStart(myObject.ThreadFunction) );
thread.Start(myObject)
In the exact example you give, simply by accessing this.
In the general case, you can also do something like
class SomeClass {
public void ThreadFunction(object param)
{
var justAnExample = (string)param;
}
};
SomeClass myObject = new SomeClass();
Thread thread = new Thread(myObject.ThreadFunction);
thread.Start("parameter");
This allows you to pass a parameter of any type (here, a string) to the thread function. If you need more than one, then you can always pass in a Tuple or an object[] or any other container of values.
If you go this way, you might want to make ThreadFunction static (this will lose you the option of using this) as well.

How To Pass refrence and Get Return in Thread?

I Working on desktop application where i am get struck.
I have a method through I am doing HTTP Post And Get. I am managing this object through ref in entire application.
This object fetching category from website and i am using same ref for posting as well.
This category Fetcher method return datatable of categories. This Method hang my UI, So i need to implement this in thread.
But i don't know how to pass ref in thread and get return values.
This is How I am passing values.
Categorydt = objPostDataFetcher.FetchCategories(ref httpHelper);
I want to call this method in Thread. Please give me any idea and suggestion.
Thanks in Advance.
I think this should solve the problem of passing ref.
new Thread(() => { YourMethod(ref httpHelper);
in your case, it looks to be
new Thread(() => { objPostDataFetcher.FetchCategories(ref httpHelper);
And if you want to use method with return type in thread, you can use this link
how to call the method in thread with aruguments and return some value
Good Luck :)
The simplest approach would be to use an asynchronous delegate, as this will give you parameter passing and return values. However, it is worth bearing in mind that this will run on a thread-pool thread and may not be suitable if your calls are very long-running. Anyway, start with delegates and see how it performs. There is a good tutorial here:
http://msdn.microsoft.com/en-us/library/h80ttd5f.aspx
If don't want your method to hang user interface you should use BackgroundWorker class. Look at http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx.
Best regards.
Here's how to invoke a worker method on its own thread that invokes a callback to pass data back to the main thread:
class Program
{
public static volatile bool done = false;
static void Main(string[] args)
{
WorkerClass worker = new WorkerClass();
worker.Callback = new WorkerCallbackDelegate(WorkerCallback);
System.Threading.Thread thread = new System.Threading.Thread(worker.DoWork);
thread.Start();
while (!done)
{
System.Threading.Thread.Sleep(100);
}
Console.WriteLine("Done");
Console.ReadLine();
}
public static void WorkerCallback(object dataArg)
{
// handle dataArg
done = true;
}
}
public delegate void WorkerCallbackDelegate(object dataArg);
class WorkerClass
{
public WorkerCallbackDelegate Callback { get; set; }
public void DoWork()
{
// do your work and load up an object with your data
object data = new object();
Callback(data);
}
}

How to create an asynchronous method

I have simple method in my C# app, it picks file from FTP server and parses it and stores the data in DB. I want it to be asynchronous, so that user perform other operations on App, once parsing is done he has to get message stating "Parsing is done".
I know it can achieved through asynchronous method call but I dont know how to do that can anybody help me please??
You need to use delegates and the BeginInvoke method that they contain to run another method asynchronously. A the end of the method being run by the delegate, you can notify the user. For example:
class MyClass
{
private delegate void SomeFunctionDelegate(int param1, bool param2);
private SomeFunctionDelegate sfd;
public MyClass()
{
sfd = new SomeFunctionDelegate(this.SomeFunction);
}
private void SomeFunction(int param1, bool param2)
{
// Do stuff
// Notify user
}
public void GetData()
{
// Do stuff
sfd.BeginInvoke(34, true, null, null);
}
}
Read up at http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx
try this method
public static void RunAsynchronously(Action method, Action callback) {
ThreadPool.QueueUserWorkItem(_ =>
{
try {
method();
}
catch (ThreadAbortException) { /* dont report on this */ }
catch (Exception ex) {
}
// note: this will not be called if the thread is aborted
if (callback!= null) callback();
});
}
Usage:
RunAsynchronously( () => { picks file from FTP server and parses it},
() => { Console.WriteLine("Parsing is done"); } );
Any time you're doing something asynchronous, you're using a separate thread, either a new thread, or one taken from the thread pool. This means that anything you do asynchronously has to be very careful about interactions with other threads.
One way to do that is to place the code for the async thread (call it thread "A") along with all of its data into another class (call it class "A"). Make sure that thread "A" only accesses data in class "A". If thread "A" only touches class "A", and no other thread touches class "A"'s data, then there's one less problem:
public class MainClass
{
private sealed class AsyncClass
{
private int _counter;
private readonly int _maxCount;
public AsyncClass(int maxCount) { _maxCount = maxCount; }
public void Run()
{
while (_counter++ < _maxCount) { Thread.Sleep(1); }
CompletionTime = DateTime.Now;
}
public DateTime CompletionTime { get; private set; }
}
private AsyncClass _asyncInstance;
public void StartAsync()
{
var asyncDoneTime = DateTime.MinValue;
_asyncInstance = new AsyncClass(10);
Action asyncAction = _asyncInstance.Run;
asyncAction.BeginInvoke(
ar =>
{
asyncAction.EndInvoke(ar);
asyncDoneTime = _asyncInstance.CompletionTime;
}, null);
Console.WriteLine("Async task ended at {0}", asyncDoneTime);
}
}
Notice that the only part of AsyncClass that's touched from the outside is its public interface, and the only part of that which is data is CompletionTime. Note that this is only touched after the asynchronous task is complete. This means that nothing else can interfere with the tasks inner workings, and it can't interfere with anything else.
Here are two links about threading in C#
Threading in C#
Multi-threading in .NET: Introduction and suggestions
I'd start to read about the BackgroundWorker class
In Asp.Net I use a lot of static methods for jobs to be done. If its simply a job where I need no response or status, I do something simple like below. As you can see I can choose to call either ResizeImages or ResizeImagesAsync depending if I want to wait for it to finish or not
Code explanation: I use http://imageresizing.net/ to resize/crop images and the method SaveBlobPng is to store the images to Azure (cloud) but since that is irrelevant for this demo I didn't include that code. Its a good example of time consuming tasks though
private delegate void ResizeImagesDelegate(string tempuri, Dictionary<string, string> versions);
private static void ResizeImagesAsync(string tempuri, Dictionary<string, string> versions)
{
ResizeImagesDelegate worker = new ResizeImagesDelegate(ResizeImages);
worker.BeginInvoke(tempuri, versions, deletetemp, null, null);
}
private static void ResizeImages(string tempuri, Dictionary<string, string> versions)
{
//the job, whatever it might be
foreach (var item in versions)
{
var image = ImageBuilder.Current.Build(tempuri, new ResizeSettings(item.Value));
SaveBlobPng(image, item.Key);
image.Dispose();
}
}
Or going for threading so you dont have to bother with Delegates
private static void ResizeImagesAsync(string tempuri, Dictionary<string, string> versions)
{
Thread t = new Thread (() => ResizeImages(tempuri, versions, null, null));
t.Start();
}
ThreadPool.QueueUserWorkItem is the quickest way to get a process running on a different thread.
Be aware that UI objects have "thread affinity" and cannot be accessed from any thread other than the one that created them.
So, in addition to checking out the ThreadPool (or using the asynchronous programming model via delegates), you need to check out Dispatchers (wpf) or InvokeRequired (winforms).
In the end you will have to use some sort of threading. The way it basically works is that you start a function with a new thread and it will run until the end of the function.
If you are using Windows Forms then a nice wrapper that they have for this is call the Background Worker. It allows you to work in the background with out locking up the UI form and even provides a way to communicate with the forms and provide progress update events.
Background Worker
.NET got new keyword async for asonchrynous functions. You can start digging at learn.microsoft.com (async). The shortest general howto make function asonchrynous is to change function F:
Object F(Object args)
{
...
return RESULT;
}
to something like this:
async Task<Object> FAsync(Object args)
{
...
await RESULT_FROM_PROMISE;
...
return RESULT;
}
The most important thing in above code is that when your code approach await keyword it return control to function that called FAsync and make other computation until promissed value has been returned and procede with rest of code in function FAsync.

Why does an instance of a generic class get altered on a separate thread when an instance of an ordinary class does not?

When an object is altered in a method that runs on a separate thread, the object is not altered on the calling thread (the thread that started the thread on which the method runs).
However, if the class that defines the object is generic, the object gets altered on the calling thread. For example:
I have two classes:
public class Holder<T> { public T Value {get;set;} }
And
public class Holder2 { public String Value {get;set;} }
I have a third object called client which on method Change() sets the Value to something different on a separate thread:
static void main(string[] args)
{
Holder<String> test = new Holder<String>();
test.Set("original");
Client client = new client(test);
client.Change(test);
Console.WriteLine(test.Value);
// test.Value now returns "changed"
// But if test was of type Holder2, it would return "original"
}
So basically what client does is:
public class Client
{
Holder<String> test;
public Client(Holder<String> test)
{
this.test = test;
}
public void Change()
{
ThreadStart ts = new ThreadStart(Alter);
Thread t = new Thread(ts);
t.Start();
}
public void Alter()
{
test.Value = "changed";
}
}
However, If I change the Client class to instead take Holder2, which isn't generic it does no longer work. That is to say, test.Value would return "original". Can anyone please explain to me, why is that?
Since you do not use locking there is a race-condition which might explain your observations.
Also: Please show how you display the variable after calling the client.Change(test);

Categories

Resources