.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Post New Web Links

Wait for threadpool to finish

Posted By:      Posted Date: September 23, 2010    Points: 0   Category :.NET Framework
I want to have a ThreadPool of "worker" threads that wait to be signaled to work. Once signaled it does its work then loop back to beginning and waits to be signaled again. I know how to use manual and auto resetevents to signal the thread. The only way I can see to accomplish this is to use an AutoResetEvent to toggle each thread to do work and hold for more work and use a for loop to in the main thread to call Join() on all threads. This doesn't seem elegant. Any suggestions?

View Complete Post

More Related Resource Links

how to know when a user finish his file download successfully ?


hi all

i am doing a page to sell files online

 the paying method is by a card or bank account and the customer is not registered to the site so i want to make sure that the customer has downloaded the file successfully after that the system completes the payment operation

so if there is any way to know do that tell me please

i use c# thanx all



.NET Matters: Ordered Execution With ThreadPool


This month we demonstrate how you can use the ThreadPool to support ordered execution without having to build custom thread pools yourself.

Stephen Toub

MSDN Magazine February 2009

Net Matters: Round-Robin Access To The ThreadPool


Stephen Toub shows you how to add round-robin scheduling support on top of the ThreadPool for more granular processing control.

Stephen Toub

MSDN Magazine January 2009

Bugslayer: Wait Chain Traversal


Windows Vista has a new API called Wait Chain Traversal (WCT), which allows you to determine when and why a process is deadlocked. Read on.

John Robbins

MSDN Magazine July 2007

Windows 2000: Asynchronous Method Calls Eliminate the Wait for COM Clients and Servers


Windows 2000 is the first version of COM to support asynchronous method calls, which permit clients to make nonblocking calls to COM objects and objects to process incoming calls without blocking the calling threads. COM clients benefit from asynchronous method calls because they can continue working while waiting for outbound calls to return. Objects benefit because they can queue incoming calls and service them from a thread pool. Our SieveClient and SieveServer sample apps demonstrate how to create and use asynchronous clients and servers in COM-based distributed applications.

Jeff Prosise

MSDN Magazine April 2000

ThreadPool with lock isn't thread safe

Hello, I'm having some problems with my code which apparently isn't thread safe at all. The problem is that it doesn't crash often, but of course it does when in production! I have twisted my mind around the problem for a month or so now, and I need some help in sorting out the problem. Well, the problem is that it isn't thread safe, and the collection (_subscribers) is modified while looping. The error says that it crashes in the method: SendRoundSettings. Here's part of the code (which I guess contains the error, as the other methods are pretty much identical): [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)] public class DuplexService : IDuplexService { private readonly object _syncRoot = new object(); private static Subscribers _subscribers = new Subscribers(); private static RoundSettings _currentRoundSettings = new RoundSettings() {CompetitionId = 1, NumberOfAthletesInRound = 0, Round = 0, SortDirection = SortDirection.ByStartNumber}; public void SendJudgeScore(CompetitionJudgeAthleteJump judgeScore) { ThreadPool.QueueUserWorkItem(state => { Subscribers clonedSubscribers = CloneSubscribers(); Console.WriteLine("Sending judgeScore to {0} client(s)", clonedSubscribers.Count(x => x.CompetitionId == judgeScore.CompetitionId));

How to wait for a Serial Port to respond

Hi Is it to possible to wait for a serialPort component to complete it's response?  I have a device connected to the serial port of my PC. I use the serialPort component in order to communicate with the device. I have to send 2 different strings of data to the serial port but the trick is that after sending the first string of data I have to wait for the serial port to respond. Then I have to check the response and decide whether I must send the second string or not. Also after sending the second string, I have to check also the response of the serial port. I tried to use an arbitrary amount of wait time between the sending of the two strings. Something like SerialPort.Write(...) ; Thread.Sleep(2000); SerialPort.Write(...); But the software failed when I tried it in a slower PC. So is there a way to replace the Thread.Sleep(2000) with a command that will wait until the serial port complete its response? Although, the response of the serial port is different between the two sending strings, I do know that the first response is only one byte and I know the ending byte of the second response. Also, the second response is no more than 30 bytes in length. Regards Dimitris

Concurrency: Throttling Concurrency in the CLR 4.0 ThreadPool

The trend toward manycore architectures and parallel apps has resulted in many changes to the CLR 4.0 ThreadPool. If you're emphasizing concurrency in new apps or adding it to old ones, or making use of ASP.NET or Parallel Extension technologies, this is for you.Erika FuentesMSDN Magazine September 2010

Execute Command and wait until finished (WMI - ManagementClass)

Hi allI am trying to execute a command on a remote maschineand wait until the command is finished.I can start the process but I do not know how to wait for finish.Thanks for any comment !!!Best regardsFrankHere is what I am doing            System.Management.ConnectionOptions local_Connection = new System.Management.ConnectionOptions();            local_Connection.Username = "some_user";            local_Connection.Password = "some_password";            local_Connection.Authority = "ntlmdomainome_domain";            // ManagementScope erstellen            System.Management.ManagementScope local_Scope = new System.Management.ManagementScope("\\\\servername\\root\\CIMV2", local_Connection);            local_Scope.Connect();            // ManagementClass erstellen            System.Management.ManagementClass local_ClassInstance = new System.Management.ManagementClass(local_Scope, new System.Management.ManagementPath("Win32_Process"), null);            // Create a results and completion handler            System.Management.ManagementOperationObserver local_ClassHandler = new System.Management.ManagementOperationObserver();            // Invoke method asynchronously            System.Management.ManagementBaseObject local_InParams = local_ClassInstance.GetMethodParameters("Create");            local_InParams["CommandLin

Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential cau

Attempting to upgrade from SQL 2005 EE to SQL 2008 EE on Vmware ESX 3.5 virtual server. below is info from Detail.txt related to successful install with failures... 2010-09-02 13:50:46 Slp: Sco: Attempting to check if file 'D:\Data\MSSQL.1\MSSQL\LOG\ERRORLOG' exists 2010-09-02 13:50:46 Slp: Sco: Returning security descriptor O:BAG:SYD:AI(A;ID;FA;;;S-1-5-21-3788118842-658835432-3441893140-1006)(A;ID;FA;;;S-1-5-21-3788118842-658835432-3441893140-1007)(A;ID;FA;;;BA)(A;ID;FA;;;SY)S:AI(AU;IDFA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD) 2010-09-02 13:50:46 Slp: Configuration action failed for feature SQL_Engine_Core_Inst during timing ConfigRC and scenario ConfigRC. 2010-09-02 13:50:46 Slp: Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes. 2010-09-02 13:50:46 Slp: Configuration action failed for feature SQL_Engine_Core_Inst during timing ConfigRC and scenario ConfigRC. 2010-09-02 13:50:46 Slp: Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineConfigException: Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes. 2010-09-02 13:50:46 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlServerServiceBase.WaitSqlServerStart(Process processSql) 2010-09-02 13:50:46 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlServerServiceSCM.StartSqlServer(St

Wait for an activity to complete?

I have the following scenario:My workflow (Workflow1) has a custom activity which inserts data into the database.My program creates an instance of WorkflowApplication (passing an instance of Workflow1) and runs the instance.Thereafter, it reads the data that has been inserted in the execute method of my custom activity. How do I know that the execution of the activity is complete? I am running in issues as the workflow instance seems to run on its own thread.Code snippet:Program.cs  // create the WF instanceActivity wf = new WorkflowTests.MicroLoanOrignation(); WorkflowApplication instance = new WorkflowApplication(wf){                PersistableIdle = OnIdleAndPersistable,                Completed = OnWorkflowCompleted,                Idle = OnIdle}; instance.Run(); //Gets data here..//Enters into this code block before the Execute method of the lst activity of the workflow is complete How do I make it synchronous. I have have tried BeginRun and EndRun methods on the WorkflowApplication - but the Run method merely schedules the workflow to run as per https://connect.microsoft.com/VisualStudio/feedback/details/509928/workflow

Producer/Consumer using ThreadPool.RegisterWaitForSingleObject?

Hi, I'm trying to implement an abstract daemon class for a producer/consumer scenario using ThreadPool threads. I came up with: public abstract class ThreadPoolExecuter { private AutoResetEvent _Signal; private bool _IsStopped; protected bool IsStopped { get { return _IsStopped; } } public virtual void Start() { _Signal = new AutoResetEvent(false); ThreadPool.RegisterWaitForSingleObject(_Signal, new WaitOrTimerCallback(Signalled), null, -1, true); } protected void Signal() { _Signal.Set(); } void Signalled(object notUsed, bool timedOut) { if(_IsStopped) return; try { Execute(); } catch(Exception ex) { OnError(ex); } if(!_IsStopped) ThreadPool.RegisterWaitForSingleObject(_Signal, new WaitOrTimerCallback(Signalled), null, -1, true); } protected abstract void Execute(); protected abstract void OnError(Exception ex); } The idea is that different classes could inherit from this, and use their own Execute() implementation depending on their needs. The inheriting class would Signal() whenever it needed to execute some job on the ThreadPool. I have one such inheriting class implementing a Queue for a producer/consumer scenario. My problem is that sometimes my application (a web app hosted on IIS7) seems to miss events. No error is logged. This is obviously a very hazy description of the problem, so what I want to ask is this

How to Wait for the Completion of the BookmarkCallback method?

Hi I have a custom activity, which create a bookmark. In the callback method, I am setting some data to the object, which I need back to host application. It is just like protected override void Execute(NativeActivityContext context) { context.CreateBookmark(EventName, new BookmarkCallback(this.HandleEvent));} private void HandleEvent(NativeActivityContext context, Bookmark bookmark, object obj) { if (obj != null) { Dictionary<string, object> dat = obj as Dictionary<string, object>; dat.Add("NewValue", "value1"); } } From the host, I am resuming the bookmark as workflowApp.ResumeBookmark("Next", data); if (data.ContainsKey("NewValue")) { newValue = data["NewValue"].ToString(); } ResumeBookmark will execute only when the WorkflowApplication goes Idle; so I am not getting the value back just after the ResumeBookmark. How can I wait for the Completion of the ResumeBookmark? I tried with the BeginResumeBookmark() & EndResumeBookmark() methods too. EndResumeBookmark() doesn't mean that the callback method execution is completed. Either, I need to make the WorkflowApplication to go Idle state or I need to wait for the completion of the ResumeBookmark(Callback method completion). Note:  We are using the UI thread for executing the workflow          &n

ThreadPool max threads

Hi All, I'm writing an application to do some basic load tests. To start with I wanted to make sure I understood the ThreadPool. Can someone tell me why the below application seems to pause after launching 4 threads on my machine? Thanks Warrick  class Program { static void Main(string[] args) { load doit = new load(); for(int i=0; i < 10; i++) { // ThreadPool.SetMaxThreads = 20; ThreadPool.QueueUserWorkItem(new WaitCallback(doit.dowork),(object)i); } Thread.Sleep(10000); } } class load { public void dowork(object o) { Console.WriteLine("Start "+o.ToString()); Thread.Sleep(1000); Console.WriteLine("Done" + o.ToString()); } }

How to run multiple methods asyncronously and wait until all are finished?

I have this method:   public virtual List<User> GetUsersAsync(string[] usernames) { var result = new List<User>(); foreach (var username in usernames) { result.Add(this.GetUser(username)); } return result; }   Currently this method and GetUser run synchronously. How can I change this so that each GetUser runs asynchronously and GetUsers returns when all the GetUser() requests are completed? I know one way would be using delegate beginInvoke and endInvoke like this:   public virtual List<User> GetUsers(string[] usernames) { var result = new List<User>(); var delegates = new Dictionary<GetUserDelegate, IAsyncResult>(); // begin invoke all asynchronously foreach (var username in usernames) { var thisDelegate = new GetUserDelegate(GetUser); var asyncResult = thisDelegate.BeginInvoke(username, null, null); delegates.Add(thisDelegate, asyncResult); } // end invoke all foreach (var thisDelegate in delegates) { result.Add(thisDelegate.Key.EndInvoke(thisDelegate.Value)); } return result; }   this does work but seems to be a bit ugly code; what is the better way to do this? Thanks  

Finish Page

Is there some event like Page_Load but to close the page ?
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend