Click here to Skip to main content
15,887,998 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
first of all there is no code problem, so if you are code solver or something ignore this, i want to do something but i dont know if its efficient, to make it simple, i have one line code
C#
this.dt = new DateTime.Now;

but i want to make it in thread, for example

C#
public void SetDateTime()
{
this.dt = DateTime.Now;
}


and i want to call it in thread,

C#
Thread d = new Thread(SetDateTime());
d.Start();


i will still use this method, only IF when the thread finishes the job, it automatically dispose itself, since i will use this in timer on 1000ms, which means on every second, there will be thread holding memory in ram, so after job done, will the thread dispose itself? kinda strange question but...
Posted
Comments
Mehdi Gholam 11-Sep-15 11:53am    
Threads are for long running processes which is clearly not the case for your method.

Threads are objects and will be garbage collected when not referenced.
Sergey Alexandrovich Kryukov 11-Sep-15 12:01pm    
1) Threads are not really objects.
2) All unreachable objects will be eventually garbage-collected; it's not related to threading.
3) Note that dt is some member, not a local variable, so it can have reference on it from anywhere.
I answered this question, please see Solution 1.
—SA

1 solution

The question does not make sense; and it is not really related to threading, as formulated.

There is nothing you could do not "in thread", even if your thread is only one.
Also, dt cannot be "disposed", but it will be garbage-collected. Garbage collections and disposal are different things; read on these topics.

And it does not matter on what thread you do the call. The only issue is the reachability of objects. If you keep some reference to the object of the class declaring dt, it will be kept in memory. Please learn how it works: https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29[^].

Of course, if you share any object, such as dt, between threads, you need to do this through mutual exclusion mechanism, one of the ways of thread synchronization:
https://en.wikipedia.org/wiki/Mutual_exclusion[^],
https://msdn.microsoft.com/en-us/library/ms173179.aspx[^],
https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx[^].

—SA
 
Share this answer
 
Comments
Mehdi Gholam 11-Sep-15 12:32pm    
5'ed
Sergey Alexandrovich Kryukov 11-Sep-15 12:51pm    
Thank you, Mehdi.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900