Click here to Skip to main content
15,880,725 members
Everything / General Programming / Threads

Threads

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 Title

Threads 

6 Jan 2014 by JayantaChatterjee
Hi all,I create a form which have some function perform on the form_load, at the meantime I want to show a form(like "please wait").I used Background Worker. My code is :-private void QuestionForm_Load(object sender, EventArgs e) { WP = new WorkerProgress();//here...
7 Jan 2014 by OriginalGriff
You cannot access controls exactly from the thread that they were created on: the UI thread.You are trying to access them from your BackgroundWorker, which is a different thread entirely.Either use the Invoke method to access them, or move the code into the UI thread via the...
7 Jan 2014 by Rahul VB
Hello Mam, When ever we start a form based application, the application starts on a single UI thread. Now if i perform some operation using some of its controls. Suppose, on button click, perform some calculation. If the calculation is small its okay, but as the work to be done grows,...
10 Jan 2014 by Rahul VB
Hello Mam, look at the code below: class Class1 { static TableLayoutPanel tlp; public Class1(TableLayoutPanel TLP) { tlp = TLP; } public void doWork(object sender,DoWorkEventArgs e) { ////perform...
11 Jan 2014 by Alan N
Hi Jayanta,I was reading the discussion you were having with OriginalGriff and I wonder if the real problem is the poor performance of Microsoft's TableLayoutPanel. If you are having issues with redraw then enabling double buffering on the control will speed it up. I have found that on .NET...
5 Nov 2015 by Manidas Payyoli
I am trying to use the method "Dispatcher.BeginInvoke" in a Windows Phone 8.1 Universal App.However, "Dispatcher.BeginInvoke" seems not to be existing!"using System.Windows.Threading;" also does not exist!I get the error message that the namesepace does not exist and I may be missing...
5 Nov 2015 by Richard Deeming
You already have the necessary code underneath the BeginInvoke line, but commented out:public async void XMPPClient_OnStateChanged(object sender, EventArgs e){ switch (xmppClient.XMPPState) { case XMPPState.Ready: if (IsXmppSuccess) { ...
4 Sep 2019 by honey the codewitch
I have a component that keeps a cache on a per-thread basis, but in some applications i need to share the cache across multiple threads. I don't mind hosting the component on a thread and then marshalling calls over to/onto that thread in order to share the cache between other threads - in fact...
2 Sep 2019 by Gerry Schmitz
System.Collections.Concurrent Namespace | Microsoft Docs[^]
4 Sep 2019 by George Swan
You can use lock to restrict the updating of a variable to one thread at a time. Other threads calling the method will be blocked until the lock is released. private readonly object totalLock = new object(); private double total; public void AdjustTotal(double amount) ...
6 Jun 2014 by SD1208
Hello all,I've been working on adding functionality to a program I'm working on and would like to use std::Threads to add multi-threading. What I've noticed is that when adding #include a compilation error occurs with the error-error C2371: 'int8_t' : redefinition; different basic...
6 Jun 2014 by KarstenK
you got to change the included headers. Exclude the header which you REALLY NEED ("primary"), to find the part where else it is defined and try to exlude it, or include the "secondary" header AFTER the "primary".It is in most cases somehow an configuration problem of your project.
6 Jun 2014 by leon de boer
KarnstenK sort of gives you the correct answer but it needs expandingThere are two units both trying to define "int8_t" and one of those is part of the standard C library it will be in "StdInt.H" in the system include directory of any C99 compliant compiler.Fixed width integer types...
12 Aug 2015 by Hamish Ahern
just put the word "signed" so that the compiler knows it for suretypedef signed __int8 int8_t;typedef signed __int16 int16_t;typedef signed __int32 int32_t;typedef signed __int64 int64_t;typedef unsigned __int8 uint8_t;typedef unsigned...
12 Aug 2015 by CPallini
int8_t should be defined in cstdint header. Possibly a non-standard header redefines it. I am pretty sure the compiler is reporting what are the conflicting headers.
3 Apr 2017 by Howard ( Chaim) Davis
For resource monitoring i need to know how much resources are being consumed. Is there a good way to know which parent a thread belongs to. from there I can log usage per thread... What I have tried: I can pass the parent id in a thread start, but there are so many other way to start a...
3 Apr 2017 by Dave Kreskowiak
There is no such thing as a parent-child relationship between threads in .NET. You have to setup a structure and tracking mechanism to do this yourself. Some method of launching threads and placing the data in the structure and removing it when threads terminate. I fail to see why you would...
3 Apr 2017 by Wessel Beulink
Why do you not use the visual studio performance window? I can't think of any reason of 'monitoring' this in a none-debug version. Beginners Guide to Performance Profiling[^]
7 Aug 2015 by Member 3084160
I'm testing the ThreadStatic attribute in a simple class.Here's the code:public class TestClass { [ThreadStatic ( )] static int reps = 0; [ThreadStatic ( )] static int count = 20; public void Run ( ) { var t1 =...
7 Aug 2015 by Member 3084160
Find out by myself looking on MSDN.https://msdn.microsoft.com/en-us/library/system.threadstaticattribute.aspx[^]Remainder for me: RTFM!
7 Aug 2015 by Sergey Alexandrovich Kryukov
This is because count is thread-static, one task is using this value, and another one uses hard-coded immediate constant 20 (bad by itself). A thread-static field becomes not static, the attribute ThreadStaticAttribute makes it behave as two or more different static fields per each thread, which...
13 Dec 2011 by Freeboss
Hi, I am looking for a way to set a Fixed concurrent tasks number..As far as i know Task.Factory does not have anything like and i'm stuck.I've also though about the BlockingCollection and the Producer-Consumer model but i'm not sure if this is the right implementation as i have about...
13 Dec 2011 by E.F. Nijboer
Have a look at the ThreadPool class and TaskScheduler class. And... I think the third link might be a good example of what you are looking...
16 Sep 2013 by Jeankininho
HiBasically, I'm using the class of .Net MessageQueue, I send a Message with FileName to a Queue, but I've received many errors from the Machines that consume the Queue like "File doesn't exist" or "FileNotFoundException". The machines supposed to delete the files.If someone familiar...
17 Sep 2013 by Mehdy Moini
Imagine one thread is completed and another thread is not, so thread one, after endReceive , will delete the file when second thread have a message queue with a file name which doesn't point to a file, because first thread delete that.
2 Aug 2020 by Evgeny Pereguda
Clone of PCSX/PCSX2/PPSSPP emulator for Windows 10 on WPF/C# with "touch" control
15 Mar 2013 by FreakyLOL
Hello.I am going to write a simple chat programm with WinSock.It should work peer-to-peer so each program is server and client.I need to run a method ever in a new thread.How can I realize this?Is it possible to return something from that method?Thanks.P.S.: I'm from...
15 Mar 2013 by Sandeep Mewara
Posting it to pop it out of unanswered list. OP resolved it by himself with help from this: Multithreading Tutorial[^]
15 Aug 2010 by Teamsar Muliadi
Hi experts, i wanna ask u about multithread with some parameters. I've a problem when i want to send some parameters. :( I have three methods and three parameters in each other :private void SendAckDetail(string memberID, string partName, string AccNum){ //-- process}private...
15 Aug 2010 by PSK_
You can try like following.class Program { static void Main(string[] args) { ThreadTest t = new ThreadTest(); Acknowledgement acknowledgement= new Acknowledgement(); acknowledgement.AccNum = "123"; ...
21 Dec 2017 by Greek Varak
I have a c# code that calls a dll (cpp build) and writes a text file (of 12 MB size) of txt file to a variable by calling a cpp dll Getting following errors : {"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."} Additional information:...
11 Sep 2015 by SrgjanX
first of all there is no code problem, so if you are code solver or something ignore this, i want to do something but i dont know if its efficient, to make it simple, i have one line codethis.dt = new DateTime.Now;but i want to make it in thread, for examplepublic void...
11 Sep 2015 by Sergey Alexandrovich Kryukov
The question does not make sense; and it is not really related to threading, as formulated.There is nothing you could do not "in thread", even if your thread is only one.Also, dt cannot be "disposed", but it will be garbage-collected. Garbage collections and disposal are different things;...
8 Jun 2020 by zarovsky
I have a for loop that in each iteration goes through a list of url and grabs the tag of each one and then writes it to a file. here is the code: #!/usr/bin/env python import os import requests from bs4 import BeautifulSoup import time,...
7 Jun 2020 by OriginalGriff
You need to be aware that threading is not a "magic bullet" that will solve all your performance woes at a stroke - it needs to be carefully thought about and planned, or it can do two things: 1) Slow your machine to a crawl, and make your...
15 Jun 2015 by Andy Lanng
Hi,I have some code that gets a list of tasks from a db message queue. and yields results. This is running quite slowly so I want to multi-thread it. How can I best implement a multi-threaded version of this:private IEnumerable GetData(){ while (!_cancel) { ...
15 Jun 2015 by Andy Lanng
Edit: The solution I went for including tweaks.If you follow the comments, my issue is that there is once process that takes all the time in my ProcessMessage method. There is barely anything I can do while I'm waiting for it to do it's stuff so async was not much of an improvement.I...
19 Jun 2015 by Andy Lanng
Hi,Before you type tl;dr, read the cliff-notes ^_^Some of you will be a bit familiar with my project.Basically: I read messages from the db. When I do I set a marker on the record called 'Started' to true. That way I won't read them again.I put the messages into a SortedSet. I...
23 Jul 2013 by Ken Chiayuan Chang
main function:#include #include #include "server.h"#include using namespace std;int main(){ Object_server a; Sleep(10000); return 0;}this is server.h:#ifndef SERVER_H_INCLUDED#define SERVER_H_INCLUDED#include...
23 Jul 2013 by Fredrik Bornander
This call;int_flag=_beginthreadex(NULL, 0, Object_server::accept_thread, (void *)this, CREATE_SUSPENDED, &threadID);Creates the accept thread in suspended state, you'll either have to start the thread manually by calling ResumeThread after that or, change the CREATE_SUSPENDED to 0,...
18 Dec 2013 by Hari Mahadevan
Describes a C++ class that encapsulates the WaitForMultipleObjects API usage pattern making it easy to integrate it with C++ objects.
9 Jan 2014 by Hari Mahadevan
Describes a C++ class that encapsulates the WaitForMultipleObjects API usage pattern making it easy to integrate it with C++ objects.
30 Apr 2015 by Sebastian Solnica
A case of a deadlock in a .NET application
2 Aug 2018 by Marc Clifton
A discussion of various approaches to threading, covering locks, mutexes, semaphores, concurrent collections, work queues, threads, PLINQ, TPL, exception handling, and cancellation tokens
24 Dec 2013 by Senthilvel Samatharman
This tip provides a simple implementation for the ICommand interface and enables to write quick code leaving the nuances of fetching the return types and asynchrony
24 Feb 2018 by Akhil Jain
This is my code in which a list contains 2 more lists where the WorkItem collection contains a large number of records such as 7,000 it takes 10 min. Is there any way to make it faster and in case it's deciding the workItem type if it's a bug, task or product backlog item. Please tell me how to...
24 Feb 2018 by Patrice T
I see nothing obvious. You need to understand where and how time is spent, the tool of choice is a profiler. Profiling (computer programming) - Wikipedia[^] List of performance analysis tools - Wikipedia[^] [Update] Quote: have put stopwatch before and after the loop and it show's 10 min ...
24 Feb 2018 by BillWoodruff
If you are serious about understanding time performance in .NET, I suggest you learn to use one of these open-source tools: BenchmarkDotNet (what I use) [^], or, AppMetrics [^]. By doing this, you will become a better programmer. Scott Hanselman wrote about BenchMark in 2016: [^]. Both these...
6 Jul 2015 by Sacha Barber
A brief look at using the .NET Akka framework (Akka.NET)
15 Jan 2013 by Alessandro Lentini
How to write a simple multi-thread queue for the typical producer-consumer process
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.
4 Apr 2013 by Michael Mann (mann.DEV)
Plugin migration with new features of .NET 3.5.
15 Apr 2011 by Albin Abel
Here is an example code.public class ThreadTest{ private string _file="Hello World"; private ReaderWriterLock _rw1=new ReaderWriterLock(); public void ReadFile(object obj) { _rw1.AcquireReaderLock(1000); for(int i=0;i
15 Apr 2011 by Sander Rossel
I am currently learning about multithreading. I have a book (Exam 70-536 self-paced training kit) which gives an example about multi-threading.So I have tried this (taken from the book). The code is as follows:Imports System.ThreadingPublic Class FastMemFile Private _file As...
15 Apr 2011 by Albin Abel
4 Mar 2022 by Southmountain
I tried a simple demo at an article on here, and got into an issue, which I think it is simple: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; ...
4 Mar 2022 by OriginalGriff
ref is a keyword: you can't use it as a variable name: IAsyncResult ref = delInstance.BeginInvoke(100,"I am in Delegate Thread", null, null); Change the name, it should compile.
13 May 2013 by Eduardo Antonio Cecilio Fernandes
How to build a simple Scheduler in C# for Desktop and Web Applications
15 Oct 2010 by Andre Trollip
A simple set of classes to make creating Peer to Peer messaging easy using UDP. Features built-in message concatenation and delivery receipts for reliable transmission.
1 May 2020 by honey the codewitch
Creating an application that can run once, but then accept command line args from subsequent runs
28 Oct 2010 by federico.strati
This is a standard Windows / C++ implementation of a multi-threaded queue.
17 Jun 2013 by Domus1919
Hi all,I have create this program to manage multiple threads multiple queues, for elaborate a series of images. Every thread pop an image from a queue, works on it, and push it in output queue.Thanks to different advices received here from other users, I have create this code, but the...
13 Nov 2015 by Tim Bomgardner
Make .NET threadpool threads jump through hoops with this handy support class
10 Jun 2014 by Sen Jacob
A simple task scheduler utility by which you can schedule a task to run at any time or interval
11 Jun 2014 by Sen Jacob
This is an alternative for "A Task Scheduler Library for .NET Applications"
15 Jul 2020 by honey the codewitch
How to implement a complicated multithreaded message passing scenario
13 May 2011 by Blu_pre
I have developed an application and i want to add a Datetime (digital clock) indicator on the Mdi form. But i want this indicator to be active whenever my application has delays due to long query results. I used a timer and i updated my datetime indicator label in the timer1_tick event. So...
13 May 2011 by OriginalGriff
So, that's what you want.I want $100,000,000 in small, used notes.Do you think it is likely either of us is going to get what we want without at least some effort?In my case, I would have to rob a very big bank, win a lottery, or just invent a FarceBook killer app.In your case, you...
13 May 2011 by Karthik. A
Your form freezes because it's not multi-threaded. In a single threaded model, the lone thread would be busy dealing with your actions causing the form to freeze. In your case it cannot return back from the method that runs your time consuming loop. You need delegate tasks like this to another...
24 Jul 2011 by hofingerandi
A tiny application to launch a process suspended to allow, e.g., attaching a remote debugger.
2 Nov 2011 by gndzero
A threaded application to identify if system VB6 OCX files are exploitable and generate a batch file to register updated OCX controls.
7 Oct 2012 by Andriks
A MessageBox replacement with some much needed extras
9 Apr 2015 by Member 11185261
Hi!How do I abort completed tasks. I have used the following code: - class Program { static void Main(string[] args) { System.Timers.Timer myTimer = new System.Timers.Timer(); myTimer.Elapsed += new ElapsedEventHandler(OnTimer); ...
9 Apr 2015 by Duncan Edwards Jones
You have created an array to hold tasks, but not actually put any tasks in it.Therefore you have an array of { null, null, null, null, null, null, null, null, null, null}In your first test you have if (tasks[i] != null && so the rest of the if does not get evaluated.Then it gets to the...
11 Aug 2013 by MyOldAccount
Hello my fellow colleagues from CodeProject! I will try to be brief, so I will cut to the point:I work on Windows XP, in C++, using pure Win32 to create a dialog box.That dialog box has some edit controls, and OK button, which activates a thread when pressed.Thread then gathers...
10 Aug 2013 by Nitheesh George
Hi Nenad,I suggest, you should use thread synchronization mechanism such as a Event to do you job perfectly. And then use WaitForSingleObject windows API to wait for the event to be signaled. When done with your thread, I mean after completing the writing to word document, set the event as...
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...
11 Aug 2013 by H.Brydon
Others have posted here some very good advice, which I will not contradict. Several comments from me:(1) your IDOK handler does not end with a "break;" statement, and as shown, will drop through to the IDCANCEL code. In the IDOK logic, you close the handle, then use it in the IDCANCEL logic....
31 Jul 2015 by Michael Breeden
OK, I think I know... the problem is I might be wrong.In general, if a variable is guaranteed to be written to by only one thread, it can be read by others with no problem. Correct?More specifically, I could use a ConcurrentDictionary, but don't think it is necessary. The idea is that a...
31 Jul 2015 by Sergey Alexandrovich Kryukov
If one thread reads from a dictionary, and another writes to dictionary, this dictionary is required to be thread-safe. But you can use a collection which is not thread-safe, because you can sandwich both operations (or all other operations accessed from different threads of the same collection...
30 Sep 2018 by Steven Coco
This illustrates a simple pattern that provides a lock that can always be invoked; and may be a no-op for a non-synchronized implementation.
8 Feb 2011 by All Time Programming
Hello, I have a dialog (WaitingDialog) that is mainly used to display the happening activities. It has a Title & Message that sets the respective labels.public string Title { get { return title; } set { title = value; label1.Text = title; }}public string...
9 Feb 2011 by Sergey Alexandrovich Kryukov
I answered very similar question before, please see the code: Changes step by step to show a control[^].You will need to work with your server is the background worker, of course.Another solution would be having a permanent thread created from the very beginning and post UI changes from...
11 Jun 2013 by greatnishant
Notepad is a basic text-editing program and it's most commonly used to view or edit text files. A text file is a file type typically identified by the .txt file name extension.
30 Mar 2012 by V.
You should be able to use the Dispatcher[^] property on that. Use the Disptachers CheckAccess() method the check how to access the control. (note CheckAccess does not appear in intellisense.)Here's a sample where the backgroundworker thread calls the SetMsg function to update the label...
30 Mar 2012 by fjdiewornncalwe
This article explains this topic very well. You should use the search functionality on CP to see if the answers to your questions already exist. Cheers.Accessing Windows Forms Controls across Threads[^]
29 Jun 2010 by foreversunshyne
I have a the following function CreateAudiTrail (AuditTrail ATObj).In this function I call first the Create sp and then the Update sp.I want to track (without using triggers) the call made to these sps.I will start a thread, threadCreate for the execution of Create Sp. One create is over,...
29 Jun 2010 by sainath437
Hi.. Just check out for InstanceMAnagement in WCF.instancemanagement-persession in wcf
15 Jul 2010 by Ramin Tarhande
I am not sure if I have understood you well, but here is my suggestion:You want to wait till the thread is done; right? If so call threadCreate.Join(). This call will block till the thread is done.I guess that you don't need something like a session here and the problem is more related to...
20 Mar 2013 by Pranit Kothari
Hi,We started working on Multithreaded application which will serve high TPS (transaction per second) messages. We need to write platform independent code which will work on Windows as well as on Linux. So, we are planning to use library for multithreaded programming. I searched through...
20 Mar 2013 by Eugen Podsypalnikov
A very good readable library[^] :)"Qt is a full development frameworkwith tools designed to streamline the creation of applications and user interfacesfor desktop, embedded and mobile platforms."
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...
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...
19 Dec 2012 by Kieran Crown
Okay, I want to add multiple user controls into a flow panel at one time without the UI freezing, I've tried adding the controls from a Background Worker but get an error about how it cannot be added because it can't change parent control or something like that, any help would be appreciated.
19 Dec 2012 by Adam R Harris
You are going to have to create a delegate to add the controls for you, something like this:** assuming your flow control is called 'flow' private delegate sub delAddControl(ctrl as Control) private sub AddControl(ctrl as Control) if (flow.InvokeRequired) then ...