Multi Threading [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm learning Multi Threading at the moment, in C#, but as with all learning I like to learn best practices. At the moment the area seems fuzzy. I understand the basics, and I can create threads.
What should I look out for when creating multi threaded applications. Are there any set rules or best practices that I should know about? Or anything to remember in order to avoid slip ups down the line?
Thanks for the responses.

In addition to the MSDN Best Practices, I'll add:
Don't make your own threads. Prefer to use the ThreadPool (or the new Task Parallel Library Tasks). Managing your own thread is rarely, if ever, the correct design decision.
Take extra care with UI related issues. Control.Invoke (Windows Forms) and Dispatcher.Invoke (WPF), or use SynchronizationContext.Current with Post/Send
Favor using the BackgroundWorker class when appropriate.
Try to keep synchronization via locks to a minimum
Make sure to synchronize everything that requires synchronization
Favor the methods in the Interlocked class when possible over locking
Once you get more advanced, and are trying to optimize, other things to look for:
Watch out for false sharing. This is especially problematic when working with arrays, since every array write to any element in an array includes a bounds check in .NET, which in effect causes an access on the array near element 0 (just prior to element 0 in memory). This can cause perf. to go downhill dramatically.
Beware of closure issues, especially when working in looping situations. Nasty bugs can occur if you're closing on a variable in the wrong scope when making a delegate.

MSDN - Managed Threading Best Practices
That MSDN Article does a really good job at touching on the danger areas and giving the best practices for managing/working around those areas.

Since I have this open on another tab...
http://www.yoda.arachsys.com/csharp/threads/
I'm only a couple chapters in but it was written by Jon Skeet.

Are there things you should know about ?
Certainly.
Dangers:
Race Conditions
Deadlocks
A usefull and interesting article can be found here

I highly recommend that you start by digesting this: http://www.albahari.com/threading/.

Related

Can someone please explain (nicely) why OOP Method Overloading is a good thing? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
First, please no spamming because I am not necessarily an OOP devotee. That said, I have been a programmer on and off for almost 30 years and have created a lot of pretty cool production code systems/solutions in several industries. I've also done my share of break/fix, database development, etc. Even a bout 10 years as a web programmer, not developer, so I an not so much a newbie but someone trying to get an answer about something that frankly is eluding me.
I started as a "C" programmer int he early 1980's and "C" served me well into the early 2000s (even today most scripting and higher level languages use "C" syntactical elements).
That said, overloading seems to violate every principle of what I was taught were "good coding practices" by increasing ambiguity in the opportunity for omission of intended code to be executed for a given condition or actually running a routine you didn't expect to due to some condition falling through the cracks. Also generally seems to creates LOTS of confusion for learners.
I am not saying overloading is bad per se, I just want to better understand it's practical application to real problems other than simply a way to provide input validation or perhaps just to handle inputs from other sources that you have no control over in an API or something else that you don't necessarily know the type of (again not clear on how or why that could actually happen either) C# has a lot of parse and try catch to handle this as do most OOP languages.
In over a decade, I have yet to get a straight, non judgmental and dare I say unsnarky answer to this question. Surely there is someone who can offer a reasonable explanation of why it is used.
So I pose the question to you the stack overflow gurus, Personally, does having a method/function that is potentially callable multiple different ways with multiple exclusive code segments really a good thing, or does it just suggest lack of good planning when designing software. Again, not knocking, judging, or disparaging, I just don't get it.....please enlighten me!
I'd say std::to_string is a pretty good example of good use of overloading. Why would you want to have different functions for converting different types to std::string? You don't. You just want one - std::to_string and you want it to behave sensibly whatever type of argument you give it - and it does just that. Using overloading keeps the client code simple.

Could you please explain this statement by providing an implementation of the design pattern it alludes to? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
The Managed Threading Best Practices page states:
Avoid providing static methods that alter static state. In common server scenarios, static state is shared across requests, which means multiple threads can execute that code at the same time. This opens up the possibility of threading bugs. Consider using a design pattern that encapsulates data into instances that are not shared across requests. Furthermore, if static data are synchronized, calls between static methods that alter state can result in deadlocks or redundant synchronization, adversely affecting performance.
I understand all the rest except for the one sentence that is in bold.
How would you do this without essentially changing the field from a static one to an instance one? Isn't that saying, "In a server scenario, avoid using static class-level members as much as you can?"
If it isn't, could you please provide an implementation of the design pattern it is alluding to?
How would you do this without essentially changing the field from a static one to an instance one?
No one can possibly answer this question without knowing why you thought that putting something in a static field was a good idea in the first place.
Isn't that saying, "In a server scenario, avoid using static class-level members as much as you can?"
No. To be clear, that is a good idea. But that's not what this sentence is trying to communicate. It is saying if you have a problem that you think could be solved by making a static method that modifies static state, then maybe you should consider finding some other way to solve the problem.
If it isn't, could you please provide an implementation of the design pattern it is alluding to?
Design patterns exist to solve problems. You haven't said what problem you're solving, so it's impossible to recommend a pattern.
Look, suppose you're planning on constructing a building on sand, and I tell you that only fools build on sand, and you then say OK, give me a design for a building that still meets my needs, but not built on sand. I don't know what your needs are and I don't know why you thought that building on sand was a good idea in the first place, so no, I can't do that. But that does not change the fact that only fools build on sand.
Are you thinking of modifying static state in a multithreaded server scenario? That's a really foolish thing to do. Find another way to do whatever you want to do. How? I haven't the faintest idea; I don't know what you're trying to do. But that doesn't change the fact that you're unlikely to be successful by modifying static state on a multithreaded server.

using a class or a function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Sorry for the noob question but I've always had a hard time distinguishing situations when it's good to create a function or a class. For some of the smaller programs I write at work, I write a whole bunch of functions to carry out specific tasks. The programs all work as intended. However, when I have some of my more senior developers take a look to give me their critique, they rewrite a lot of my functions completely over as a class. These are my coworkers so I don't want to look completely incompetent (I just started this job as a junior developer) by asking them why they did that. What do you guys think?
That is too broad question and you really have to understand the concept of the Object Oriented Programming and when you should use it.
Note: Bellow you will find my personal opinions (some of them borrowed from great books' authors and experienced programmers), and for sure the things highlighted bellow, does not reflect the entire power of the Object Oriented thinking and design. These will be gained throughout experience and feedback.
0. A use case of a class
There are many applications, on where to use an internal class to your C# code.
Data Transfer Object (DTO)
One application (of really many) and is used many times in software, is when you are transmitting data from database to your application for processing.
What better than writing an internal class that will store your data, implement useful and re-usable methods that can be used later in your application logic (e.g isAdministrator) and so on.
1. Object-Oriented Design Patterns
I will recommend you reading a book about Object-Oriented Design Patterns.
Books like that, describe some problems scenarios that can be implemented with a class using a pattern. Once you have read about these patterns and possible scenarios on where can be used, you will be able to get the book, find the pattern and solve your problem.
A co-worker of mine, state something really useful. When you are facing a problem, you should ask yourself:
"Does this problem solved again using a design pattern?"
If the answer is yes, then you go back to your reference book to find your design pattern, that will solve your problem, without re-inventing the wheel.
This approach, will teach you how and when you should use a separate class; but will also help you to maintain a communication language between you and your co-workers, that is, if you are talking about your code to a co-worker, you will be able to state the design-pattern and you will be immediately understood (given that, your co-worker know about the specific design-pattern).
2. Don't be afraid creating more than one internal classes
Another note, don't afraid to create multiple internal classes. Implement as much as possible, don't try to implement one internal class and mix responsibilities. Your class should be for a specific purpose, and should not do more than one thing (i.e responsibilities, if you are writing a class that is about transmitting data from your database to your application logic, should not - ideally - doing something else, like adding data to your database).
Consider learn more about Polymorphism, Inheritance, Encapsulation and Abstraction.
These four fundamental principles of Object Oriented Programming can also help you to learn how to structure your code object-oriented.
3. General Notes
As a Junior-Developer and not only as a Junior but as a Developer in general, you should always willing to learn from the more experience guys, by asking for feedback. Is not a shame is the law of learning and improve your code.
Another powerful source of learning, is books, consider buy some for the area you are interested in. (e.g Object Oriented Programming, Design Patterns etc).
As others noted in comments, this is really too broad and slightly opinionated, but big picture, use a class when:
You maintain state over time, and apply functions to this state.
You have a set of functions that share a common goal or deal with a common usage, data type or otherwise "obvious shared idea". That's particularly relevant when these functions can be reused in other places.
But really, to get a deeper understanding, get a book :-)
BTW, in C#, you can't put any functionality outside of a class, so the question should really be "how to divide my monolith class to smaller classes"

Advantages/disadvantages of combining C# and C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am thinking about developing Winforms application that would use c library to preform all computations. I want to use C# because developing GUI with it is really easy, and C to increase performance. Are there other advantages or any disadvantages of combining those two languages?
Edit: As computations I mean mainly (but not limited to) graph algorithms, like coloring, dijakstra, maximum flow; I expect graphs to be huge, and performance is really crucial.
and C to increase performance
You could write pretty well performing applications using pure managed code. Take for example this very same site. It's pretty darn fast, don't you think?
The way I see things is the following: mix those two technologies only if you are really some kind of a performance maniac (someone that tries to solve the scaling problems that Google does for example) or if you have some existing C codebase that you cannot port to .NET immediately and that you have to interoperate with.
In other cases, managed code is safer. If you are sick about performance don't forget that in many cases the cost of marshaling between managed and unmanaged code will be higher than the performance you would gain from pure unmanaged code. Also the JITter gets smarter and smarter with each version of the framework and maybe one day it will generate almost as efficient code as unmanaged code.
So, yeah, go for managed and leave C to the maniacs :-)
I would not be so sure that C will be faster than C# for what you are going to do. The jitted code is extremely fast. Also, if you are doing lots of calculations, by using c#/.net, you could potentially take advantage of the Task Parallel Library, which would greatly ease parallelizing your calculations. And really, with all of the multi-core machines, I think that you will get a lot more bang for your bucks if you can take advantage of multiple cores (of course, straight C can thread as well, but the TPL in .net 4 is much more productive than the base WinApi)
One other thing that you might consider, and I am speaking from outside of my own experience, so definitely do your own research: I have heard that F# can be a very good choice for writing scientific sets/calculation libraries. I haven't written a line of F# myself, but from what I understand, the language design supports writing the calculations in a way that makes them extremely parallelizable.
(of course, now you have a new problem -- learning F# ;)
there is a post here that you might check out: F# performance in scientific computing
Getting fixed memory locations, and also converting your indexes to C pointers could have negative side effects. You can try both safe and unsafe code for sure and try to see the results but my guess is that safe code will perform better at the end. For sure, your computation is also important factor.
I have done this in the past, I would say that as other mentioned the cost of marshalling is not free so you need some pretty specialised need before this is a valid option.
My only advice to you would be to start in the most adapted language, which would be C# if you want to have managed code and other features that C# provide. And then if performance is an issue and do some profiling and optimise carefully by adding some code in C after weighting the pro/cons and considering whether you can get some optimisation by reworking the high level algorithm rather than optimising at a lower level.
For example, if you were to write scientific code, you would make your code multithreadable or checking that you cannot reuse previous computations before to attempt other kind of lower level optimisation, this will have a much larger impact on your efficiency rather than chasing tiny problems.

C# Open Source software that would benefit from parallelization? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm not sure if this kind of question is appropriate, but its been suggested I ask here, so here goes.
For a subject at university this semester our assignment is to take some existing code and parallelize it. We've got a bit of an open end on it, but open source is really the only way we are going to get existing code. I could write some code and then parallelize it, but existing code (and perhaps one where I could make a genuine contribution) would be best, to avoid doubling my workload for little benefit.
I was hoping to use C# and make use of the new Task parallel library, but I'm struggling to find some C# open source projects that are computationally expensive enough to make use of parallelization (and don't already have it).
Does anyone have some suggestions of where to look? Or is C# just not going to have enough of that kind of thing as open source (should perhaps try C++?)
I don't know if they already use parallel tasks, but good candidates are image manipulation programs, such as paint.net or pinta.
I don't know the scope of this project (if it's just a weekly assignment or your final project), but a process that benefits from parallelization does not have to be "embarassingly parallel" as Hans' linked article describes. A problem will benefit from being parallelized if:
The solution to the problem can be expressed as the "sum" of a repetitive series of smaller operations,
The smaller operations have minimal effect on each other, and
The scale of the problem is sufficient to make the benefits of parallelization greater than the loss due to the added overhead of creating and supervising multiple worker processes.
Examples of problems that are often solved linearly, but can benefit from parallelization include:
Sorting. Some algorithms like MergeSort are atomic enough to parallelize; others like QuickSort are not.
Searching. BinarySearch cannot be parallelized, but if you're searching unordered data like a document for one or more occurrences of words, linear searches can use "divide and conquer" optimizations.
Data transformation workflows. Open a file, read its raw data, carve it up into domain fields, turn those domain fields into true domain objects, validate them, and persist them. Each data file is often totally independent of all others, and the process of transformation (which is everything between reading the file and persisting it) is often a bottleneck that benefits from having more processors thrown at it.
Constraint satisfaction problems. Given a series of business rules defining relationships and constraints of multiple variables in a problem space, find a set of those variables that meets all constraints, or determine that there are none. Common applications include transportation route scheduling and business process optimization. This is an evolving sector of computational algorithms, of relatively high academic interest, and so you may find published public-domain code of a basic CSP algorithm you can multithread. It may be described as embarassingly parallel as the best-known solution is "intelligent brute force", but nonetheless, a possible solution can be evaluated independently of others and so each can be given to a worker thread.
Processes defined as "embarassingly parallel" are generally any problems sufficiently large in scale, yet atomic and repetitive, that parallel processing is the only feasible solution. The Wiki article Hans links to mentions common applications; they usually boil down, in general, to the application of a relatively simple computation to each element of a very large domain of data.
Check out Alglib, especially the open source C# edition. It will contain a lot of matrix and array manipulations that will be nicely suitable for TPL.
Project Bouncycastle implements several encryption algorithms in C# and java. Perhaps some of them are not as parallelized as they could be.

Categories