|
Which is why I made the suggestion that I did.
Unrequited desire is character building. OriginalGriff
I'm sitting here giving you a standing ovation - Len Goodman
|
|
|
|
|
better way is to ask for more information about the question.!!!
@faraz34 : what exactly you would like to achieve ? whats your problem ?
thanks
-Amit.
|
|
|
|
|
Not at all; I gave an answer which may be the right one. If not then OP can respond with more details.
Unrequited desire is character building. OriginalGriff
I'm sitting here giving you a standing ovation - Len Goodman
|
|
|
|
|
the ways of an MVP, you should treat with the greatest respect!
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|
If you referring to writing classes with an extensive amount of code. Then I'd suggest you use the "partial" key word. That way you can spread your class over separate files. In each file you just call the full declaration of the class but with the partial key word. Eg;
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}
http://msdn.microsoft.com/en-us/library/wa80x488%28v=vs.80%29.aspx[^]
|
|
|
|
|
faraz34 wrote: How can we write the long source of a program in
2 or 3 files and relate them together at build time.
1. Design your application so that you can break the functionality into classes. Classes normally are rather small. This step has nothing to do with actually writing code.
2. Implement each class in a different file.
3. In C# you put all of the classes in a project which is then managed via a solution.
|
|
|
|
|
jschell wrote: 3. In C# you put all of the classes in a project which is then managed via a
solution.
You mean "in Visual Studio"; C# neither knows nor cares about projects and solutions.
|
|
|
|
|
csc /out:My.exe *.cs
Will compile all .cs files within that folder into My.exe. Snippet taken from MSDN[^].
Bastard Programmer from Hell
|
|
|
|
|
Yes, but I use /recurse:"*.cs"
|
|
|
|
|
In addition to using *.cs you can also put the specific files:
csc MyFirstClass.cs MySecondClass.cs etc.cs
The name of the first will be used to name the output (i.e. MyFirstClass.exe in this case) unless you specify a /out: target.
IDEs generally hide this away from you – are you writing code in a text editor? You don't normally need to do that, as there are good free IDEs available for .Net.
|
|
|
|
|
Hi I would like to use argument in ThreadStart Delegate but I have problem with syntax. here the code example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace mtquestion
{
class Program
{
static void Main(string[] args)
{
Thread T1 = new Thread(new ThreadStart(C(15,25)));
Thread T2 = new Thread(new ThreadStart(C(15, 29)));
Thread T3 = new Thread(new ThreadStart(C(18, 25)));
T1.Start();
T2.Start();
T3.Start();
object locker = new object();
lock (locker)
T1.Join();
T2.Join();
T3.Join();
lock (locker)
Console.Write("c");
}
public static void C(double a, double b) { Console.WriteLine(a*b);}
}
}
the syntax
Thread T1 = new Thread(new ThreadStart(C(15,25)));
return the following error"method name expected"
How can I pass arguments?
Thanks for your time
|
|
|
|
|
In order to pass arguments, you need to look at using a ParametrizedThreadStart instead:
Thread T1 = new Thread(new ParameterizedThreadStart(Y));
T1.Start(42);
...
public static void Y(object i) { Console.WriteLine("Hello: "+ i); }
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
|
|
|
|
|
Thanks a lot for answer
Just last help: suppose I need many parameters let's say a double, a DateTime[] and a Dictionary<>,
How can I manage only using the parameter (object i).
To be more clear, I have something like:
public static void Y(double a, DateTime[] myDates, Dictionary<string,double> myDic)
I suppose there is a workaround to fit all in object and using casting.
thanks for your time
|
|
|
|
|
Personally, I would create a TaskParameter class with the required properties and pass over a single instance to the task. If nothing else, it gives a nice object for locking should that prove necessary later.
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
|
|
|
|
|
Hi,
you don't need the locks you have:
1. Thread.Join() is thread-safe by itself, you adding locks does not help a bit. This is not documented, however it should be obvious as the thread executing the join is doing nothing but wait.
2. Console output is thread-safe also, otherwise Console output would most always be garbled as most apps have several threads. This too is not documented AFAIK.
Locks do make sense when you have one or more methods that:
- want access to the same data;
- AND can be executing at the same time, which implies by different threads.
And even then, for atomic operations, you still wouldn't need a lock (but you may need the volatile keyword). Atomic here means the data operation is performed by a single assembler instruction, e.g. a 32-bit int load or store; a set of atomic items (e.g. a struct) is itself not atomic, so if two ints need to represent a consistent state, then you also would need a lock. When in doubt about atomocity, be safe and use a lock.
And lock objects must be accessible by all methods involved, so a local variable can not serve that purpose. It should be a class member. And for safety, it shouldn't be public: it should be accessible only to the objects that need access.
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|
Thank you for your very good answer. My question was incomplete.
Basically I also need a thread called "total" that sum the "y" calculated in C.
For do that I have 2 problem:
-> total has to wait each C to finish
-> total has to get data from each C (how passing data?)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace mtquestion
{
class Program
{
static void Main(string[] args)
{
Thread T1 = new Thread(new ParameterizedThreadStart(C));
Thread T2 = new Thread(new ParameterizedThreadStart(C));
Thread T3 = new Thread(new ParameterizedThreadStart(C));
T1.Start(15000000);
T2.Start(25000000);
T3.Start(60000);
T1.Join();
T2.Join();
T3.Join();
Console.WriteLine("All 3 done");
}
public static void C(object i)
{
double y = 0.0;
for (int j = 1; j<(int) i; j++)
{
y += Math.Log(Math.Exp(0.06)) * Math.Log(Math.Exp(0.06)) / Math.Log(Math.Exp(0.06)) * Math.Log(Math.Exp(0.06));
}
Console.WriteLine(i);
}
public static void Total(object j)
{
C(..) when conclueded
}
}
}
|
|
|
|
|
There are dozens of ways to get a total result from the work of several threads. I'll list just a few:
1.
have a single variable "double total" accessible by all thread methods involved; now let each threaded method add its result to it. This is a situation where you need a lock (you shouldn't allow multiple threads to read and write the total value at exactly the same time).
2.
have a single queue accessible by all threads; each threads pushes its result to the queue; when all is done (after the join point), the main thread pops everything from the queue and calculates the sum. As the typical queue isn't thread-safe, here too you'll need a lock.
2bis.
like 2, but using some synchronization means to have yet another thread calculate total. See e.g. ManualResetEvent type.
3.
much simpler: have a little job class, which is intended to hold all the input parameters and the results of each thread. Instantiate one instance for each job/thread, have the thread get its values from there, and store its results in there as well. Also maintain a collection of these jobs, so the totalizer can enumerate the jobs and accumulate their results.
4.
often my preference: like #3, however put the actual job code also inside the job class, which means all threading code is encapsulated there too. Here is an example:
class Job {
private int parm1;
private int parm2;
public int Result;
private Thread thread;
public Job(int parm1, int parm2) {
this.parm1=parm1;
this.parm2=parm2;
}
public void Run() {
thread=new Thread(new ThreadStart(runner));
thread.Start();
}
public void Join() {
thread.Join();
}
private void runner() {
Result=parm1+parm2;
}
}
class Test {
public static Main() {
List<Job> jobs=new List<Job>();
for(int i=0; i<10; i++) {
Job job=new Job(3*i, i+12);
jobs.Add(job);
job.Run();
}
foreach(Job job in jobs) job.Join();
int total=0;
foreach(Job job in jobs) total+=job.Result;
}
}
I suggest you read up on all the classes/types I mentioned, and better yet, read about threading in your C# book.
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|
Luc Pattyn wrote: Atomic here means the data operation is performed by a single assembler instruction, Although it happens to be true for your examples (and it's often true), it's not true in general.
For example:
add dword ptr[esp+0x20], eax
inc dword ptr[edi]
(but of course lock prefixes could be added)
Luc Pattyn wrote: so if two ints need to represent a consistent state, then you also would need a lock There's even an exception to that: lock cmpxchg8b (assuming 32bit)
But I'm pretty sure you know all that, so this is Wittgenstein's ladder?
|
|
|
|
|
Yep, I think I'm well aware of the underlying stuff. There is a lot to consider, the intermediate language doesn't help transparency, the target platform doesn't have to be x86/x64, etc. So better be safe than sorry; the one class I often find useful (for simple things at least) is Interlocked .
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|
If you're using .Net 4, look at the Task Parallel Library. It is designed specifically for running parallel tasks which is what you appear to be trying to do here.
In the old days I would create a thread (now I'd name it task, but this comes from the Java model where I first learnt multithreading) class that stored the state of a particular operation:
class MyTask {
double a,b;
Thread t;
ManualResetEvent wh;
ManualResetEvent WaitHandle { get { return wh; } }
public Thread Thread { get { return t; } }
MyTask(double a, double b) {
this.a = a; this.b = b;
t = new Thread(new ThreadStart(Run));
wh = new ManualResetEvent();
}
private void Run(){
wh.Signal();
}
}
... and call it like
Thread thread = new MyTask(11, 15).Thread;
thread.Start();
or, if you care about the wait handle:
MyTask task = new MyTask(11, 15);
task.Thread.Start();
task.WaitHandle.WaitOne();
But I do stress that the TPL will do all this stuff fairly nicely without requiring you to write code.
|
|
|
|
|
thanks a lot for your answer
I will study TLP. It first sight it looks really very nice
|
|
|
|
|
Hi there
Im pretty new to C# and im having a real problem when i getting data from my MySql Database.
Firstly I read the data in to a Datatable then i read it in to a Dictionary(Like vb Collection) however when i tried to convert it straight to a string i comes out as DBNULL this was pretty annoying!!
so to get round it it tried conveting it to datetime first and then to string which worked as long as im stepping over, then when i ran it normally i got
'Object cannot be cast from DBNull to other types.'
this is really annoying
when it brings me back in to the code i can see that it has taken the data in the datetime var but still kick up the error
if (datatype == "MySql.Data.Types.MySqlDateTime")
{
DateTime Ddata = Convert.ToDateTime(dt.Rows[0][colname]);
data = Convert.ToString(Ddata);
}
else
{
data = Convert.ToString(dt.Rows[0][colname]);
}
I'll be real grateful if someone can help with this as im Stumped
Regards Ian
|
|
|
|
|
I guess that the field in the database can contain a null value, and whenever you get the error, you hit a row where that column actually was null. Hence check first:
if (dt.Rows[0][colname] != DBNull.Value) ...
|
|
|
|
|
Hi Bernhard
Thanks for your reply
well in this instance the code is only getting one row.
the database is set up to accept nulls but for this record i know there is a value there.
when i look at the datatable in dataset visualizer (Whilst de-bugging) i can see that the value is there.
i do a check very simerlar to your lower down but that just disregards the date and puts it as null. I only wrote that if statement to catch MySQL dates as they didn't seem to be working, i figured if i converted to a date first that it would be ok.
I was wrong
Ian
|
|
|
|
|
... and when it is a DateTime, just cast it, no need to convert:
System.DateTime dt = (System.DateTime) dt.Rows[0][colname] ;
Alternatively, if you really want the date in a string (which you shouldn't until you output it, just use ToString:
string dt = dt.Rows[0][colname].ToString() ;
or, to output to the console:
System.Console.WriteLine ( "DateTime={0}" , dt.Rows[0][colname] ) ;
In summary: Don't ever use the Convert class -- except for the ChangeType method when necessary.
|
|
|
|