I have console application. In that i have some process that fetch the data from database through different layers ( business and Data access). stores the fetched data in respective objects. Like if data is fetched for student then this data will store (assigned ) to Student object. same for school. and them a delegate call the certain method that generates outputs as per requirement. This process will execute many times say 10 times. Ok? I want to run simultaneously this process. not one will start, it will finish and then second will start. I want after starting 1'st process, just 2'nd , 3rd....10'th must be start. Means it should be multithreading. how can i achieve this ? is that will give me error while connection with data base open and close ?
I have tried this concept . but when thread 1'st is starting then data will fetched for thread 1 will stored in its respective (student , school) objects. ok? when simultaneous 2'nd thread starts , but the data is changing of 1'st object ,while control flowing in program. What have to do?
Here is some sample code:
static void Main(string[] args)
{
for (int i=0; i<10; i++)
System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(DbWork));
}
public void DbWork(object state)
{
// Call your database code here.
}
Have a look at the ThreadPool class. It should put you in the right place for easy handling of multi threaded applications
Yes this would require multithreading but I feel it makes a poor choice for a first attempt. Multithreading is complicated and requires you to "unlearn" a few things you picked up from procedural programming. This is further complicated by simultaneous database connections to the same database engine which may or may not improve your performance anyway.
Have a look at Parallel Programming in .NET 4.0. Especially the parallel task library gives you great control over threading different tasks that can have dependencies on each other.
You need to instantiate a new instance of each class for each thread. If each call to the database is modifying the data from the first call, you are referencing the same instance. Multithreading is considered an "advanced topic", you may want to find another way to solve this problem if at all possible.
this may help!
start a thread that is master thread that calls all threads 1,2,3 .... in sequence and do this logic to master thread
master thread started..
thread 1 started if first time or resumed if not first time
work completed
suspend t1
start t2 is first time
or resume t2 if not first time
t2 work complete
t2 suspend
t3 started or resumed as condition handled first
and so on for all thread
the master thread will control the sequence for all thread and suspend and resume them also
try this,
You should not implement a multithreaded solution unless you understand the mechanisms and inherent problems.
That said, when you feel you are ready to move to a parallel algorithm, use the pattern known as APM (Asynchronous Programming Model) where you spawn the worker threads and let them notify the main thread via callback methods (i.e. event delegates).
Jeffrey Richter explains: Implementing the CLR Asynchronous Programming Model
Related
I am writing a multi-thread application (using C#) where the job of each thread is to insert some data into database. As soon the thread completes its job of inserting data into database it becomes free (i.e. ready to insert another data into database). All the threads are reading data from a queue.
The problem is, how to monitor which thread has completed its current job and ready to take second job? Whether we can use C# task instead of thread and how?
Please note every thread is inserting data to the same database.
The problem is, how to monitor which thread has completed its current job and
ready to take second job?
Why would you do that? Threads created are looping until there is no data. If there is no thread (or less than wanted) and data arrives, start a new thread/task. Actually uses tasks. There is no need to monitor them. This would be ridiculously inefficient.
Whether we can use C# task instead of thread and how?
Yes, and it is as simple as "look up how to start a task, which google has an answer for". That said, your architecture likely needs adjustment - doing too many things in parallel will only waste memory, rather limit the number of active threads/tasks to a specific number.
In my opinion you should use only Task not "Task in Thread".
Tasks are more flexible and already implemented robustly. In your case you can create an Task[] (with 10 Tasks if you want) and to know if the task has completed his work you can check the Task.Result value if you have declared Task<\TResult> objects.
in this way you can have direct control of the processes during the asynchronous execution including exception handling.
Hi I have a short question regarding tasks. As far as I understand Tasks can start multiple threads in itself.
Lets say I have two hardware sensors which give me data over two different dataports.
I want to implement them as producers in my c# project and then do something with the data. Would it make sense to start the data collection in two different tasks? Or should i implement them in the same task since c# will automatically put them on different threads?
var producerWorker = Task.Factory.StartNew(() => SensorB(number));
var producerWorker2 = Task.Factory.StartNew(() => SensorA(number));
or
var producerWorker = Task.Factory.StartNew(() => Sensor_A_AND_B(number));
My second problem is: When I have two different producers in two different tasks, how do I add their data to the same BlockingCollection queue if they have different datatypes but need to be at the same position in the queue?
For example if I have queueA for SensorA, queueB for SensorB, and queueC.
Both queues can be filled at different speeds. So lets say queueA has 50 elements, but SensorB is a lot faster and already has 100 elements stored in queueB. However I need to retrieve the data in a way, so that I can place queueA[33].data and queueB[33].data in queueC[33].data. Of course I would not like to start with element33, but always with the first element which was stored in queueA and queueB....
I hope you get what i mena
Tasks are executed in whatever way the runtime thinks is the best. Generally, there's a thread pool and both tasks run on available threads. If you really need to poll two sensors in parallel, I would recommend you to use two real threads to poll and use Reactive Extensions to process the readings in sync.
Judging by your question, you should do some reading on how tasks and Async work in C#, the topic is too large to answer on stack overflow. I would recommend picking up a book, because MS. documentation is rubbish when it comes to providing a solid block of knowledge.
Brifly, a task can not start multiple threads inside itself. Conceptually, a task is a smaller unit than a thread. A single thread can process multiple tasks, so lets say you have 20 tasks, the c# runtime will have a thread-pool of, for example, 4 threads, and they will take a task each, process it, then move on to the next task, and so on.
Perhaps what you are referring to is Asyncronous operations. That's a very different beast than a thread. Basically you are asking some part of the computer to go off, do an independent piece of work, for example send data over network and notify your program when it's done, without blocking the thread in the meantime.
Avoid using Task.Factory, because it has many ways of shooting yourself in the foot.Take a look at Stephen Cleary blog. Task.Run(... is a better choice most of the time.
My best guess is that when you say:
Or should i implement them in the same task since c# will automatically put them on different threads?
You are referring to async operations.
For simplicity's sake you could create two separate tasks, and as soon as they recieve data pop it into a queue.
Your question suggests that you need to synchronize the incoming data.If that's so, a blocking queue is probably the wrong choice. Use concurrent queue instead. A different task could read QueueA[x] and QueueB[x], and buffer the incoming data. Then you could pop then onto QueueC when both A and B supply N'th result.
So i have 4 objects. Each one of them must execute up to 5 operations simultaneously and also all 4 object must be operated simultaneously. I created one thread for each object and inside 5 new threads ? I saw that after a period the threads are not executed anymore.
The question is : Is it ok to have thread in thread? or it's better to create a thread pool and run them in concurrency?
There is no such thing as "thread in a thread". Thread is entity that is global in whole process. It doesn't matter if it is created in one of other thread. The moment it is created, it becomes global and unrelated to thread it created it.
More about creating threads, you should be worried about access to shared resources and possible race conditions which might be much harder to track when threads are created in different places.
And from you description, I would recommend you to look at Task Parallel Library, which makes problems like this breeze.
It's ok. You actually need to do that sometimes, like when you're working with servers, you can create thread for each connected client from thread where you are listening for clients.
If I have 1 thread for my MMORPG server running a async socket and async packet handler, and in that 1 thread I have a static World that contains all entities in the game.
Would there be any threading issues if say, the async packet handler recieves an Attack message, resulting in a search of the entities in the world to figure out the target.
At the same time the static World Proc method is increasing the size of the Dictionary containing the monster entities adding extra monsters that spawned.
If this is all on the same thread, will the server explode?
will the server explode?
Yes, you can run into problems ("explode") because the async stuff is running on a different thread (even though you didn't create that thread explicitly) and it might access a shared object (world) at the same time as your main thread. Many datastructures (including the Dictionary) are not designed for this scenario and might crash or return the wrong answer.
The typical approach is to use locks to protect your shared objects: take the lock before modifying it, do whatever modification, and then release the lock. This way, only one thread at a time accesses the world (and its dictionary) and so everything remains consistent. Explosion averted.
Another way would be to switch to a more synchronous form of networking, perhaps for example avoiding completion handlers and instead waiting to hear from each of the players, and then acting on the inputs. This can be done very simply, but the simple way has drawbacks: any one slow player can slow the whole thing down. So sadly you're probably going to have to deal with some complexity, one way or another.
If I give answer in one line. Server will explode. As network activity and game logic is in same thread. And as you have mentioned you will be needing high network usage.
I seriously like that if you have a look to F#. It has all the things that you needed. As far as I got it from question. And few things are like collection change, and async is by default in language. Even Nodejs it is also worth trying. But again it all depends on requirement. Though I try to explain few keywords that may help you to take decision.
Non-blocking : It means thread will not be block on events. It will not wait for function to wait for another function to execute. But that doesn't mean you can't block it. In any case it is a single thread.
Async: It is some what like that. But in C# 5 async comes with keyword so you don't have to do threading part of programming.
Parallel Processing: In game development parallel processing is important. Now, that you can do with multiple thread or just use TPL.
In the case of UI based (where there are many objects) game I highly recommended that you separate processing thread and UI thread to improve user experience. Else FPS will go down while you are processing data.
Let me know if any further information needed.
Server will not go down if you take little care of it.
If on the same thread, then no. If you are doing all the work mentioned on a single thread, then there's no issue. However, as stated, if you are accessing a "shared" object instance across threads, then yes, there will be an issue, and locking will be required (using a "lock(){...}" block).
As your user base increases, you will have to keep an eye on the number of threads generated, or event messages if using a non-blocking event model for incoming requests.
On a different, yet related note, keep an eye on this C# based MMO server (with scripting support): https://dreamspace.codeplex.com/ - it may become a big help to MMO game creators very soon (will support Construct 2 by default).
What exactly do I need delegates, and threads for?
Delegates act as the logical (but safe) equivalent to function-pointers; they allow you to talk about an operation in an abstract way. The typical example of this is events, but I'm going to use a more "functional programming" example: searching in a list:
List<Person> people = ...
Person fred = people.Find( x => x.Name == "Fred");
Console.WriteLine(fred.Id);
The "lambda" here is essentially an instance of a delegate - a delegate of type Predicate<Person> - i.e. "given a person, is something true or false". Using delegates allows very flexible code - i.e. the List<T>.Find method can find all sorts of things based on the delegate that the caller passes in.
In this way, they act largely like a 1-method interface - but much more succinctly.
Delegates: Basically, a delegate is a method to reference a method. It's like a pointer to a method which you can set it to different methods that match its signature and use it to pass the reference to that method around.
Thread is a sequentual stream of instructions that execute one after another to complete a computation. You can have different threads running simultaneously to accomplish a specific task. A thread runs on a single logical processor.
Delegates are used to add methods to events dynamically.
Threads run inside of processes, and allow you to run 2 or more tasks at once that share resources.
I'd suggest have a search on these terms, there is plenty of information out there. They are pretty fundamental concepts, wiki is a high level place to start:
http://en.wikipedia.org/wiki/Thread_(computer_science)
http://en.wikipedia.org/wiki/C_Sharp_(programming_language)
Concrete examples always help me so here is one for threads. Consider your web server. As requests arrive at the server, they are sent to the Web Server process for handling. It could handle each as it arrives, fully processing the request and producing the page before turning to the next one. But consider just how much of the processing takes place at hard drive speeds (rather than CPU speeds) as the requested page is pulled from the disk (or data is pulled from the database) before the response can be fulfilled.
By pulling threads from a thread pool and giving each request its own thread, we can take care of the non-disk needs for hundreds of requests before the disk has returned data for the first one. This will permit a degree of virtual parallelism that can significantly enhance performance. Keep in mind that there is a lot more to Web Server performance but this should give you a concrete model for how threading can be useful.
They are useful for the same reason high-level languages are useful. You don't need them for anything, since really they are just abstractions over what is really happening. They do make things significantly easier and faster to program or understand.
Marc Gravell provided a nice answer for 'what is a delegate.'
Andrew Troelsen defines a thread as
...a path of execution within a process. "Pro C# 2008 and the .NET 3.5 Platform," APress.
All processes that are run on your system have at least one thread. Let's call it the main thread. You can create additional threads for any variety of reasons, but the clearest example for illustrating the purpose of threads is printing.
Let's say you open your favorite word processing application (WPA), type a few lines, and then want to print those lines. If your WPA uses the main thread to print the document, the WPA's user interface will be 'frozen' until the printing is finished. This is because the main thread has to print the lines before it can process any user interface events, i.e., button clicks, mouse movements, etc. It's as if the code were written like this:
do
{
ProcessUserInterfaceEvents();
PrintDocument();
} while (true);
Clearly, this is not what users want. Users want the user interface to be responsive while the document is being printed.
The answer, of course, is to print the lines in a second thread. In this way, the user interface can focus on processing user interface events while the secondary thread focuses on printing the lines.
The illusion is that both tasks happen simultaneously. On a single processor machine, this cannot be true since the processor can only execute one thread at a time. However, switching between the threads happens so fast that the illusion is usually maintained. On a multi-processor (or mulit-core) machine, this can be literally true since the main thread can run on one processor while the secondary thread runs on another processor.
In .NET, threading is a breeze. You can utilize the System.Threading.ThreadPool class, use asynchronous delegates, or create your own System.Threading.Thread objects.
If you are new to threading, I would throw out two cautions.
First, you can actually hurt your application's performance if you choose the wrong threading model. Be careful to avoid using too many threads or trying to thread things that should really happen sequentially.
Second (and more importantly), be aware that if you share data between threads, you will likely need to sychronize access to that shared data, e.g., using the lock keyword in C#. There is a wealth of information on this topic available online, so I won't repeat it here. Just be aware that you can run into intermittent, not-always-repeatable bugs if you do not do this carefully.
Your question is to vague...
But you probably just want to know how to use them in order to have a window, a time consuming process running and a progress bar...
So create a thread to do the time consuming process and use the delegates to increase the progress bar! :)