Click here to Skip to main content
15,610,223 members
Everything / General Programming / Threads



Great Reads

by Maxim Kartavenkov
Articles describes how to create virtual video capture source directshow filter in pure C#
by Maxim Kartavenkov
Article describes how to make H.264 Video Encoder DirectShow Filter using NVIDIA encoder API in C#
by Sergey Alexandrovich Kryukov
Addresses questions on graphics, threading with UI, form development, printing and more
by honey the codewitch
Take control of which thread your code gets executed on, and how it does

Latest Articles

by Bruno van Dooren
What to do when you want to use the current thread handle
by Bruno van Dooren
How to implement named pipe server for communicating with client apps
by Bruno van Dooren
How to implement named pipe server for communicating with client apps
by Greg Utas
Keeping a program running when it would otherwise abort

All Articles

Sort by Score


13 Oct 2012 by Maxim Kartavenkov
Articles describes how to create virtual video capture source directshow filter in pure C#
16 Jul 2012 by Maxim Kartavenkov
Article describes how to make H.264 Video Encoder DirectShow Filter using NVIDIA encoder API in C#
22 Mar 2017 by Sergey Alexandrovich Kryukov
Addresses questions on graphics, threading with UI, form development, printing and more
28 Jul 2020 by honey the codewitch
Take control of which thread your code gets executed on, and how it does
25 Feb 2016 by J.Starkl
A windows-service which can handle different operations in separate threads and which can be controlled by a small GUI program
6 Jul 2021 by Piotr Grygorczuk
Enable C++11 multithreading features in GCC for FreeRTOS
15 Dec 2014 by Hassan Mokdad
In this article I will demonstrate two things: First a very basic and simple code snippet to show how we can use task factory to make our web applications more responsive, the next part will be on how to use the SignalR to broadcast messages from the Web Server to all the clients connected.
2 Aug 2020 by Evgeny Pereguda
Clone of PCSX/PCSX2/PPSSPP emulator for Windows 10 on WPF/C# with "touch" control
11 Oct 2012 by CPallini
You may use only a static class member function as (third) argument to CreateThread (see ThreadProc callback function[^]).If you need to access class instance members from the thread routine the you may pass object's this pointer as thread function parameter.[UPDATE]change your function...
30 Nov 2015 by Nejimon CR
Implement WCF web service access from WPF with busy indicator and premature cancellation feature without using delegates, background worker, or separate event procedure
19 Feb 2016 by Wonde Tadesse
This is another solution in addition to Solution 1.User ThreadPool as shown below.ThreadPool.QueueUserWorkItem(o => plugin.PluginSendClass.SendMessage(e));
28 Aug 2021 by Mohammad Elsheimy
SynchronizationContext class and how it affects code behavior in action, and a look at Task.ConfigureAwait()
7 Oct 2012 by Maxim Kartavenkov
Article describes basic task which are requre to solve for developing your own DirectShow Splitter filters.
10 Oct 2011 by Sergey Alexandrovich Kryukov
You did not find anything simply because there is nothing special about a timer and a thread. How do you think, if you asked "how to find a sub-string on a separate thread" or "how to write a file in a separate thread", would you find a definitive answer? No. Because it does not matter what...
22 Mar 2012 by Shahin Khorshidnia
HelloLook at this:[^]And pay attention to EventWaitHandle.WaitOne[^]
13 Oct 2012 by Maxim Kartavenkov
Article describes basic tasks for implementing your own File Source DirectShow filters.
1 Jul 2019 by Lance Roberts
A tray utility for monitoring log files and popping up error messages
10 Aug 2013 by pasztorpisti
Your solution has several serious multithreading related problems. You are executing a long running task. A long running task is often but not necessarily cancelable.Here is a few rules that you should never break in case of multithreading and in case of a gui program:- The ownership of...
13 May 2014 by Michael Adaixo
Non blocking C# task cancelling
19 Feb 2016 by Mehdi Gholam
Try using Task :...Task.Factory.StartNew( () => plugin.PluginSendClass.SendMessage(e) );...
17 Jun 2022 by Mircea Neacsu
C++ thread objects and their use
19 Feb 2011 by Espen Harlinn
As I see it you the expected results - 30ms isn't all that long :)This may partly explain why you are not seeing the expected perfomance gains:[^] - while the article is quite old, this is still something we...
22 Mar 2012 by Sergey Alexandrovich Kryukov
I would like to add to the correct answer by Shahin. Using WaitOne if free from the problems of thread suspensions. If an instance of an event wait handle is not set, the calling thread waits in a special wait state. OS switches the calling thread off and do not schedule it back to execution...
11 Jun 2012 by Sergey Alexandrovich Kryukov
Please see my comments to the question. There must be a call to Thread.Abort somewhere. And your dedicate thread and the wait for the termination of the child process should have a reason, but this is not shown in your code.Exceptions are not errors. (Important point many developers miss.)...
11 Oct 2018 by DaveAuld
This is a probability based simulation that demonstrates 'Swapping' is considered the best option! We also look at the effect of multi-threading and multi-process in Python.
10 Oct 2018 by Vangos
During the past few months, I have been heavily experimenting with the Intel RealSense D415 & D435 depth camera. Today, I am going to show you how to easily transform between different coordinate systems. RealSense D415/435 is a low-cost device....
9 Dec 2022 by Bruno van Dooren
How to implement named pipe server for communicating with client apps
27 Dec 2022 by Bruno van Dooren
What to do when you want to use the current thread handle
21 Feb 2011 by Nish Nishant
Yes, that's a side effect of using an anonymous function there (which results in variable capture).Change your code to use a local variable:foreach (string s in fileEntries){ string tmp = s; var t = new Thread(() => Shrink(tmp)); t.Start();}[Update]~~~~~~~~~And...
20 Jun 2011 by CPallini
Probably yes. You should arrange a little test to verify execution times. You may also have a look at Thread Pool Pattern[^].
20 Jan 2012 by Dirk Bahle
I have posted a recent article on the ProgressViewModel to show a software design that can be used for background processing in C# 4.0. This article extends that design with the ability to ouput more than one progress.
17 Apr 2012 by Aescleal
How about sending the data as part of the message you post to the UI? Especially as it's only one word of information:LRESULT CContactFault::OnDeviceShortAddress(WPARAM, LPARAM lparam){ UINT data = reinterpret_cast(lparam); CsLoader = _T("%d"); CsTmp.Format(CsLoader,...
8 Jun 2012 by Volynsky Alex
Hi member 9093981114,maybe this article will help you?Or for example see following article:[^]Here you can see a...
17 Sep 2012 by Kuthuparakkal
Follow:Win32 Thread Pool[^]Also MS way:[^]
17 Sep 2012 by Espen Harlinn
As of Vista, Windows has built in support for thread pools. Take a look at CreateThreadpool[^]Best regardsEspen Harlinn
24 Nov 2012 by OriginalGriff
The problem is that the serial port is doing something called buffering - it is receiving the data from your microcontroller while your software is waiting for you to press a button on the keyboard. When you press the button, it fetches the next input line - which is the oldest, not the newest -...
20 Mar 2013 by Albert Holguin
Solution 2 is great... but why not just use the new threading that is in C++11? It will be standardized and supported across every platform that you can think of and most new compilers already support it (new gcc and vc compilers already support it). Usually it's a lot better to use something...
21 Mar 2013 by Espen Harlinn
Assuming you're using Visual C++, you could use COM, here is a pretty nice tutorial: A Beginner Tutorial for Writing Simple COM/ATL DLL For VS2012[^]Delphi works pretty well with COM, so accessing the COM object should be quite easy.Best regardsEspen Harlinn
19 Apr 2013 by Matthew Faithfull
As CPallini has pointed out this API requires Windows Vista at runtime and a _WIN32_WINNT >= 0x0600 at compile time in order to use it. There are plenty of other C++ Thread Pool implementations which work very well on Windows and existed before Microsoft chose to expose an API to their own....
23 Jun 2013 by Priyank Purwar
This article will help you understand Thread`s Synchronization objects with a real life example.
12 Jul 2013 by SabirDeveloper
Handler for WaitAll() and WaitAny() limitation problem.
6 May 2014 by Sergey Alexandrovich Kryukov
Long running tasks are done using threads, not timers. The only one little problem with having some extra thread performing such a long running task under the UI is that you cannot directly operate UI from that thread. This problem is solved using UI thread invocation mechanism.You cannot...
25 May 2014 by Thomas Daniels
You can achieve this by using the Threads window while debugging. If you want to switch to a thread, right-click on the desired thread and click "Switch To Thread". If you cannot find your thread, then give it a name to find it faster:yourThread.Name = "Thread Name";Now, the thread...
26 Jul 2016 by Zehaie M. Hailu
Python lends itself to the development of multi-threaded GUI and network applications.
13 Apr 2016 by Jochen Arndt
You did not show your main function which calls replace(). Because your programs terminates, you are probably not waiting for the threads to have terminated (done their job). In other words: The main thread reaches it's end and terminates before the worker threads had a chance to be...
29 Sep 2020 by OriginalGriff
Use a BackgroundWorker - it can report back to the UI thread as necessary: private void FrmMain_Shown(object sender, EventArgs e) { BackgroundWorker work = new BackgroundWorker(); ...
27 Feb 2021 by honey the codewitch
Using a popular RTOS to enable easy multithreading on your IoT gadgets
4 Mar 2010 by Simon P Stevens
This code provides SafeTrigger extension methods as a way of triggering events in a thread safe way.For details on usage, a discussion of reasons and alternatives, and a full solution download see my article on safely triggering events[^]Multiple overloads are provided for convenience to...
14 Mar 2010 by #realJSOP
First, you don't need the variable f - you'll see why in a moment.Second, your BackgroundWorker object should support cancellation so that it cleans up correctly if the user does something to dismiss the form while the worker is busy.The while statement should look something like...
21 Jul 2010 by Jimmanuel
If you want to make a thread safe wrapper for a non-thread safe object then it's generally a bad idea to expose the non-thread safe object from the wrapper. Once you've exposed them it's very difficult to ensure that consumers use them in a thread safe way which defeats the purpose of the...
27 Jan 2011 by Nish Nishant
They are 2 different things really. DoEvents just gives the current thread a chance to handle all pending messages. Ideally you should never have to use it. If you want the UI to be responsive, do all your heavy tasks in secondary threads and the BackgroundWorker makes it really easy to do this.
27 Jan 2011 by Sergey Alexandrovich Kryukov
Most important difference: DoEvents is not a multi-threading tools, it works in UI thread and passes all the messages blocking the caller for this time. That's why it usually don't resolve the problem some people hope to solve. Rule of thumb is never using it. (Manas is...
2 Feb 2011 by Manas Bhardwaj
You might want to look at Background worker[^] for this purpose.
21 Feb 2011 by Sergey Alexandrovich Kryukov
I'm answering the follow-up question:But i am still wondering that how adding a string tmp variable and passing that to the function worked.To get an idea, you should better understand what a closure is:[^].Let's...
25 Feb 2011 by OriginalGriff
No! Don't do it!Database connections are scarce system resources and should be open for as short a time as possible: Open it, read or write the database, then close and dispose the connection.Having a thread there just to check it is open and if not re-open it is not going to help...
1 Apr 2011 by Paulo Zemek
Hi, I am having a bizarre problem where I am reading a non-null variable as null when I pass it to another thread. I can make it volatile, use locks or thread barriers, but sometime it is read as null. If before reading such variable I write 3mb of data into an array, then it reads fine. So I...
1 Apr 2011 by Dave Kreskowiak
There is no way to do this in C# code. You'd have to write up a small block of code either in Intel Assembler or inside an ASM block in C, compiling to a .DLL, then call that from your C# code.More on the instructions can be found at here[^].
27 May 2011 by Sergey Alexandrovich Kryukov
Here you will find a complete source code showing how to do it. You create a thread wrapper where you can pass anything in or out and perform proper synchronization:How to pass ref parameter to the thread[^].If this is not quite clear for you how to apply the techniques to your...
14 Jun 2011 by BobJanova
To communicate with another thread, you need to use mutexes, wait handles or messages sent between them. However, as SA says, it is a Bad Idea to wait on network information, because it can freeze your application indefinitely.To do something when a background worker successfully (or...
14 Jun 2011 by parmar_punit
As the bobJanova wrote, use of BackgroundWrokder is much useful then using thread, when you want some call back or some notification.see this linkmore links...Link1[^]Link2[^]
16 Jun 2011 by Sergey Alexandrovich Kryukov
It would be unsafe to use virtual functions in C++ constructor (never try it). If you don't do this big mistake, why not? I would only recommend to start the thread later, not in constructor. This is not the rule, just easier to design your code properly.—SA
14 Jul 2011 by Sergey Alexandrovich Kryukov
You don't need to add any thread-safe features in the custom controls. Anyway, a non-UI thread cannot call any UI methods or properties. Working with UI from the non-UI thread is nevertheless possible, but the calls are dispatched to the UI thread using inter-thread invocation...
18 Jul 2011 by Richard MacCutchan
See this discussion[^] in MSDN.
3 Oct 2011 by Karthik Kalyanasundaram
Do you really need an explicit call to _endthreadex() in your thread function created using _beginthreadex()
1 Feb 2012 by Pete O'Hanlon
The standard way to do this is to Invoke onto the UI thread to update the control. Assuming you are using Windows Forms, you would do something like this:if (MyControl.InvokeRequired){ MyControl.Invoke(new System.Action(MyMethod), myUpdatignValue);}If you are using WPF, it would...
11 Apr 2012 by Code-o-mat
I think this is due to:dwEvent = WaitForMultipleObjects( EVENT_NUM, // number of objects in array ghEvents, // array of objects FALSE, // wait for any object (*) INFINITE); // INFINITE wait(*) Since you specify here that it shouldn't wait for all...
17 Apr 2012 by Jochen Arndt
In your case you are only passing an UINT value. So just pass it using the WPARAM or LPARAM parameter.When implementing a GetData() function, you should use locking inside that function and at all places where the data is written by the thread. An example:class CMyThreadClass{ ...
9 May 2012 by Guillaume Waser
WPF Progress controls and comparing related threads methods
1 Jun 2012 by Sergey Alexandrovich Kryukov
1) Both variants are very bad. This is a custom networking application, so it gives you enough freedom to avoid this polling approach. You need to use push, not pull technology (please see:[^],[^]). Polling...
27 Jul 2012 by Jochen Arndt
From the updated question and the comments, this seems to solve the problem:Using the Windows timers is often not the best choice. For periodic actions that are hardware related and/or sensitive to system load, a worker thread may be a better solution:Create a worker thread and a...
23 Aug 2012 by Sergey Alexandrovich Kryukov
It depends on how to use the locked resources. The reader-writer lock should have some overhead over the regular lock, so you can gain performance if you have the situation when most calls to this fragment of code end up getting only read-only access, and considerably fewer calls get write...
17 Dec 2012 by CPallini
Do you mean Managed Thread States [^]?
21 Jan 2013 by Andreas Gieriet
You are completely missing any thread synchronization.Make yourself a picture how many threads are involved and which instances are shared between the threads.E.g. LogWrite.WriteLine is called over multiple threads leading to unprotected _messagelist access. This allone is just a matter...
20 Mar 2013 by Matthew Faithfull
Boost, ACE and Qt all offer POSIX thread wrappers for Windows and Linux. ACE is not focused on this though, it's focused on comms and it's also aging somewhat in design terms so I wouldn't go with ACE. Both Boost and QT offer a lot more than multithreading support and in both cases you have to...
21 Mar 2013 by Matthew Faithfull
If you have the source to both parts, C++ and Delphi and you build both with C++ Builder/Rad Studio then you can call the C++ code from the Delphi and the other way around too. In that case you could do what you want with a callback. You pass the address of a Delphi function into the C++ as a...
29 May 2013 by Surendra Adhikari SA
Implimenting a message box that closes automatically using thread.
3 Jul 2013 by nv3
The specification of the thread function is not correct. Use _beginthread (&gangplank, 0, (void *)this);[AMENDED]In addition, you should wait in the destructor of your thread until the newly created workerthread has ended. What happens now is that in main you create a "d"...
21 Sep 2013 by Zoltán Zörgő
In general it is a bad idea to drive a system at it's limits. But what's the problem with having those per core counters? Aggregate them, and you get an overview. I suggest you check both approaches here:...
25 Sep 2013 by Sergey Alexandrovich Kryukov
In case my comments to the question are still unclear: as soon as you have more threads then the CPU cores (which is usually much, much less then the number of threads the system can possibly handle), adding each thread only degrades performance.Threads are used mostly to implement scenarios...
15 Oct 2013 by User 59241
ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function.From msdn:TerminateThread...
6 Nov 2013 by Bill_Hallahan
You can have the launched thread routine contain code that causes the thread routine to return. This will automatically cause ExitThread to be called. Your code can wait on the thread handle using the WaitForSingleObject function and when EndThread is called, WaitForSingleObject will unblock. ...
27 Jan 2014 by Sergey Alexandrovich Kryukov
Well, of course this implementation is inefficient as all those techniques based on polling. First, one side note: your use of struct Data is totally pointless, because it is equivalent to using static bContinue along. Also, using any global variables is generally bad, you could try to use, say,...
5 Apr 2014 by Pragmateek
Synchronization, Memory Visibility and Leaky Abstractions
24 Apr 2014 by idonotexistatall
How to make an HTTP Server and some documentation on server-side protocol
24 Jun 2014 by Dave Kreskowiak
No, threading is NOT a good solution to this. ASP.NET code only runs when a request is received from a browser. It's not running all the time.This requirement is better done as a console application executed by the Scheduled Task service in Windows.
10 Oct 2014 by Sergey Alexandrovich Kryukov
I would define UI thread is the thread where Application.Run is called. This is different from the definition of Solution 1, which is almost correct.I can explain the difference. It is possible to have two (or more) different threads, and run different UI on different thread. Those UI will...
12 Nov 2018 by Vlad Neculai Vizitiu
How to add functionality to an ASP.NET Core application outside of a request
27 Sep 2019 by Alkenso
Smart queue that executes tasks in threadpool-like manner
18 Nov 2019 by Michael Adaixo
Parallelizing ray tracing in C++
22 Feb 2020 by k5054
The problem is that the thread goes out of scope without having been joined, so the program crashes. See here[^] Assuming that this did work, you would get a crash anyway, since you have an infinite loop. Eventually you would run out of...
13 Jan 2010 by Rick Shaub
How I usually approach this type of problem is to either spawn a new thread[^] or use the ThreadPool.QueueUserWorkItem method to use a ThreadPool[^] thread. The body of the thread will do the work and end asynchronously. If you need to change any of the Form or its child controls UI...
12 Feb 2010 by Kemo72000
The reason you've got this exception is that the "BitmapImage" class is derived from "DispatcherObject", which means that only one thread can access it at the same time, any other attempt will throw that exception. But as it is derived from class "Freezable" also, you can freeze the object,...
22 Feb 2010 by Jimmanuel
Why would you want to deallocate it there? This whole thing looks kinda shaky to me. Where does execution ever leave the while loop? Where do testnumber and number ever change? Why are the 100s hard coded?Since you're passing the pointers in joblist to the thread function you can't...
29 Mar 2010 by Khaniya
this will helps you[^] :)
5 Apr 2010 by KenJohnson
I would advise the following 3 booksProgramming-NET-Components This is a good place to begin. It has about 100 pages on threading and is also the book I learned from.The next book I would read is CLR via C# - third edition This is also very good on the subject. I learned a lot from both...
21 Apr 2010 by Shog9
So does that mean the above 2 lines are identical?Yes, that's exactly what it means. The verbose version was the only way to do it in C# 1.0, and under the hood it's still what's happening - but since the delegate instantiation is fairly obvious from the context, C# 2 and later don't require...
3 May 2010 by #realJSOP
So accept the answer (there's a button there for it).