I created a question topic here: Thread error in C# Windows Form
It seems that for everything that is involved with the threading timer must use InvokeRequired methods. So, I got a bunch of things that need this. Is using this a lot going to use up a lot of computer resources?
Is using this a lot going to use up a lot of computer resources?
It doesn't necessarily use up "computer resources", but using Control.Invoke and Control.BeginInvoke does have overhead.
One good option, in many situations, is to try to batch your calls which require Control.Invoke/BeginInvoke, which attempts to minimize the number of marshaling operations.
Related
I am currently health checking an application which experiences UI stuttering during heavy usage.
Using Microsoft Concurrency Visualizer extension for Visual Studio 2015, showed that quite a lot of short-lived threads are created and stopped after ~100ms of execution.
Unfortunately, their displayed callstack is like clr.dll!0x98071 ntdll.dll!0x634fb and I am not quite sure how to extract useful information out of it.
I have no clue what is the purpose of those threads and which part of the code in the application is creating them.
How can I better identify where each one of them gets started?
In the code, I was able to grep a handful of Tasks, another of QueueUserWorkItems, several dozens of plain Thread instantiations, some System.Threading.Timer & System.Timers.Timer, no Reactive Extensions. I put breakpoints for all of them but it seems I am missing some...
I don't think those are from the threadpool because they would be displayed in synchronisation state in concurrency visualizer, instead they just end, and another one with another Id gets created later. But maybe I am misleading.
We also use a few third-party libs and a bunch of JuggerNET generated code, so maybe the origin is not even in the application itself.
I was finally able to find the culprit of those short-lived threads by looking closely at some of the cryptic callstacks, which included for instance:
mmdevapi.dll
wdmaud.drv
avrt.dll
audioses.dll
It led me to thinking that I should double check the sound alert system. It was indeed this one which spawned those threads.
Note:
I will not accept my answer however because I would like someone to share a better process or any kind of tips and tricks for diagnosing unwanted threads origin.
In C# I came across Backgroundworker component for concurrency. Although it was slightly advanced than using a plain vanila thread, I found it to be much smoother.
I have not used SwingWorker in Java yet. While doing some coding on threads I came across this reference from JavaDoc for SwingWorker as a solution for threadsafety when working with swing objects.
Question: In C# I don't recall a statement like "not threadsafe for WinForm/WPF layouts, so use BackgroundWorker". I want to know if SwingWorker can be a substitute for threads in all aspect in Java, like how BackgroundWorker is used in C#?
For a novice, should I expect same performance/smooth running/full debug support for SwingWorker?
I want to know if SwingWorker can be a substitute for threads in all aspect in Java, like how BackgroundWorker is used in C#?
While a SwingWorker, which implements Runnable, Future and RunnableFuture, can be used anywhere a Runnable or Future is used, no, I wouldn't do this. A SwingWorker is a bit more complex to set up and use vs. a basic Thread/Runnable, and you would have no benefit to using it in non-Swing situations. The SwingWorker has been built to allow for creation of background threads while at the same time ensuring that certain portions of its code is called on the Swing event thread. When run in an application without a Swing event thread, this has no meaning.
Edit
You state:
That means a proper Swing based application has a combination of SwingWorker and basic Thread/Runnable for it to run smooth.
Where do you derive this from my statements above. Your statement doesn't make sense and is certainly not what I have stated above.
That's just useless and the reason I paid more attention - because it was directed by JavaDoc with the basis "Swing isn't threadsafe".
Which is also true of most all GUI libraries.
I am creating a custom statemachine and in order to be determinist, I have to "synchronise" my transitions. I'm not sure about the word "synchronize" but what I want is that when I call a function (through EventHandler), the system is like frozen before I can call another function (through EventHandler too).
It's kinda hard to explain it precisely in english but I think you know what I mean...
I was thinking about Threading but I'd REALLY like to avoid this...
If you are looking to emulate the effect of the "synchronized" keyword from java, the best way is probably to wrap the entire method code inside
lock(this)
{
// code
}
Not sure if that's what you are looking for, but C# iterator blocks are essentially state machines.
Synchronization is when you're in a multi-threaded environment and you need to make access to resources by the threads synchronized (1 at a time). This ensures unpredictable results are not achieved when threads are changing resources while other threads are trying to access them. There are many constructs available to you in C# to handle synchronization. It all depends on what your threads are trying to accomplish.
Here is a link from MSDN that shows some simple examples: http://msdn.microsoft.com/en-us/library/ms173179.aspx
I have recently been looking at code, specifically component oriented code that uses threads internally. Is this a bad practise. The code I looked at was from an F# example that showed the use of event based programming techniques. I can not post the code in case of copyright infringements, but it does spin up a thread of its own. Is this regarded as bad practise or is it feasible that code not written by yourself has full control of thread creation. I do point out that this code is not a visual component and is very much "built from scratch".
What are the best practises of component creation where threading would be helpful?
I am completely language agnostic on this, the f# example could have been in c# or python.
I am concerned about the lack of control over the components run time and hogging of resources, the example just implemented another thread, but as far as I can see there is nothing stopping this type of design from spawning as many threads as it wishes, well to the limit of what your program allows.
I did think of methods such as object injecting and so fourth, but threads are weird as they are from a component perspective pure "action" as opposed to "model, state, declarations"
any help would be great.
This is too general a question to bear any answer more specific than "it depends" :-)
There are cases when using internal threads within a component is completely valid, and there are cases when not. This has to be decided on a case by case basis. Overall, though, since threads do make the code much more difficult to test and maintain, and increase the chances of subtle, hard to find bugs, they should be used with caution, only when there is a really decisive reason to use them.
An example to the legitimate use of threads is a worker thread, where a component handling an event starts an action which takes a long time to execute (such as a lengthy computation, a web request, or extensive file I/O), and spawns a separate thread to do the job, so that the control can be immediately returned to the interface to handle further user input. Without the worker thread, the UI would be totally unresponsive for a long time, which usually makes users angry.
Another example is a lengthy calculation/process which lends itself well to parallel execution, i.e. it consists of many smaller independent tasks of more or less similar size. If there are strong performance requirements, it does indeed make sense to execute the individual tasks in a concurrent fashion using a pool of worker threads. Many languages provide high level support for such designs.
Note that components are generally free to allocate and use any other kinds of resources too and thus wreak havoc in countless other ways - are you ever worried about a component eating up all memory, exhausting the available file handles, reserving ports etc.? Many of these can cause much more trouble globally within a system than spawning extra threads.
There's nothing wrong about creating new threads in a component/library. The only thing wrong would be if it didn't give the consumer of the API/component a way to synchronize whenever necessary.
First of all, what is the nature of component you are talking about? Is it a dll to be consumed by some different code? What does it do? What are the business requirements? All these are essential to determine if you do need to worry about parallelism or not.
Second of all, threading is just a tool to acheive better performance, responsivness so avoiding it at all cost everywhere does not sound like a smart approach - threading is certainly vital for some business needs.
Third of all, when comparing threading symantics in c# vs f#, you have to remember that those are very different beasts in theirselfs - f# implicitly makes threading safer to code as there is no notion of global variables hence the critical section in your code is something easier to eschew in f# than in c#. That puts your as a deleloper in a better place bc you dont have to deal with memoryblocks, locks, semaphores etc.
I would say if your 'component' relies heavily on threading you might want to consider using either the parallel FX in c# or even go with f# since it kind of approaches working with processer time slicing and parallelism in more elegant way (IMHO).
And last but not least, when you say about hogging up computer resources by using threading in your component - please remember that coding threads do not necessarily impose higher resource impact per se – you can just as easily do the same damage on one thread if you don’t dispose of your objects (unmaneged) properly, granted you might get OutOfMemeory Exception faster when you make the same mistake on several threads…
I have written a Winform application in C#. How can I check the performance of my code. By that I mean, how can I check which forms references are active at a given time or event, so that I can remove them if they are not required (make them available for garbage collection). Is there a way to do it using VS 2005 or any free tool. Any tutorials or guide will be useful.
[Edit] Sorry if my question is confusing. I am not looking for a professional tool, but ways to know/understand the working of my code better and code more efficiently.
Thanks
Making code efficient is always a secondary step for me. First I write the code so that it works. Next, I profile it if i am unhappy with the performance. The truth is most applications run fast enough after the first time writing them. Sometimes though, better performance is needed. Performance can be gained many different ways. It all depends on your application. I write LOB apps mainly, so I deal with alot of IO to databases, services and storage. These calls are all very expensive and need to be limited so they are my first area to optimize. I optimize by lazy-loading, eager-loading, batching calls, making less frequent calls and so on. I recently had a winforms app that created hundreds of controls dynamically and it took a long time. That's another bottleneck that I have to address. I use a profiler to measure the performance of the applications.
Use the free Equatec profiler. It will show you how long calls take and how many times a call is made. The profiler gives a nice report and visual display that can drill down the call stacks.
Red Gate Performance Profiler
...it's been said here a million times before. If you suspect performance issues, profile your application. It will tell you how long calls are taking and point out the bottlenecks in your code.
Kobra,
What you're looking for is called a Memory Profiler. There happens to be one (paid) version for .NET aptly named ".NET Memory Profiler", I've not used it extensively but it should answer the questions you're asking. There are a few others ones which will do basically the same thing, like giving you instance counts of loaded types, and help you identify when instances are not being garbage collected for one reason or another (i.e. Event Handler References, Static Properties, etc).
Hope this helps,
Dylan