Search Results

Search found 60 results on 3 pages for 'queueuserworkitem'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • C#. How to terminate a thread which has spawned another thread which is sleeping?

    - by Bobb
    I have a long running thread made from Thread.Start(). It spawns a background thread using QueueUserWorkItem which sleeps most of the time. Then the class-owner get disposed I call thread1.Join() but naturally it doesnt return because its child background thread is sleeping. What would be the right solution to gracefully terminate a thread which has other threads with little hassle? Thanks

    Read the article

  • How to terminate a thread which has spawned another thread which is sleeping?

    - by Bobb
    I have a long running thread made from Thread.Start(). It spawns a background thread using QueueUserWorkItem which sleeps most of the time. Then the class-owner get disposed I call thread1.Join() but naturally it doesnt return because its child background thread is sleeping. What would be the right solution to gracefully terminate a thread which has other threads with little hassle?

    Read the article

  • Sucky MSTest and the "WaitAll for multiple handles on a STA thread is not supported" Error

    - by Anne Bougie
    If you are doing any multi-threading and are using MSTest, you will probably run across this error. For some reason, MSTest by default runs in STA threading mode. WTF, Microsoft! Why so stuck in the old COM world?  When I run the same test using NUnit, I don't have this problem. Unfortunately, my company has chosen MSTest, so I have a lot of testing problems. NUnit is so much better, IMO. After determining that I wasn't referencing any unmanaged code that would flip the thread into STA, which can also cause this error, the only thing left was the testing suite I was using. I dug around a little and found this obscure setting for the Test Run Config settings file that you can't set using its interface. You have to open it up as a text file and add the following setting:  <ExecutionThread apartmentState="MTA" /> This didn't break any other tests, so I'm not sure why it's not the default, or why there is nothing in the test run configuration app to change this setting. Here is the code I was testing:  public void ProcessTest(ProcessInfo[] infos) {    WaitHandle[] waits = new WaitHandle[infos.Length];    int i = 0;    foreach (ProcessInfo info in infos)    {       AutoResetEvent are = new AutoResetEvent(false);       info.Are = are;       waits[i++] = are;         Processor pr = new Processor();       WaitCallback callback = pr.ProcessTest;       ThreadPool.QueueUserWorkItem(callback, info);    }      WaitHandle.WaitAll(waits); }

    Read the article

  • How to configure maximum number of channels in WCF?

    - by Hemant
    Consider following code which calls a calculator service: static void Main (string[] args) { for (int i = 0; i < 32; i++) { ThreadPool.QueueUserWorkItem (o => { var client = new CalcServiceClient (); client.Open (); while (true) { var sum = client.Add (2, 3); } }); } Console.ReadLine (); } If I use TCP binding then maximum 32 connections are opened but if I use HTTP binding, only 2 TCP connections are opened. How can I configure the maximum number of connections that can be opened using HTTP binding?

    Read the article

  • C# Improvement on a Fire-and-Forget

    - by adam
    Greetings I have a program that creates multiples instances of a class, runs the same long-running Update method on all instances and waits for completion. I'm following Kev's approach from this question of adding the Update to ThreadPool.QueueUserWorkItem. In the main prog., I'm sleeping for a few minutes and checking a Boolean in the last child to see if done while(!child[child.Length-1].isFinished){ Thread.Sleep(...); } This solution is working the way I want, but is there a better way to do this? Both for the independent instances and checking if all work is done. Thanks

    Read the article

  • C# How to kill parent thread

    - by Royson
    A parent has several child threads. If user click on stop button the parent thread should be killed with all child threads. //calls a main thread mainThread = new Thread(new ThreadStart(startWorking)); mainThread.Start(); //////////////////////////////////////////////// startWorking() { ManualResetEventInstance = new ManualResetEvent(false); ThreadPool.SetMaxThreads(m_ThreadPoolLimit, m_ThreadPoolLimit); for(int i = 0; i < list.count ; i++) { ThreadData obj_ThreadData = new ThreadData(); obj_ThreadData.name = list[i]; m_ThreadCount++; //execute WaitCallback obj_waitCallBack = new WaitCallback(startParsing); ThreadPool.QueueUserWorkItem(obj_waitCallBack, obj_ThreadData); } ManualResetEventInstance.WaitOne(); } I want to kill mainThread.

    Read the article

  • Java's ThreadPoolExecutor equivalent for C#?

    - by chillitom
    Hi Guys, I used to make good use of Java's ThreadPoolExecutor class and have yet to find a good equivalent in C#. I know of ThreadPool.QueueUserWorkItem which is useful in many cases but no good if you want to control the number of threads assigned to a task or have multiple individual queues for different task types. For example I liked to use a ThreadPoolExecutor with a single thread to guarantee sequential execution of asynchronous calls.. Is there an easy way to do this in C#? Is there a non-static thread pool implementation? Thanks, T.

    Read the article

  • Can running object be garbage collected?

    - by Kugel
    I have a simple class: public class Runner { public void RunAndForget(RunDelegate method) { ThreadPool.QueueUserWorkItem(new WaitCallback(Run), method); } private void Run(object o) { ((RunDelegate )o).Invoke(); } } And if I use this like so: private void RunSomethingASync() { Runner runner = new Runner(); runner.FireAndForget(new RunDelegate(Something)); } Is there any danger using it like this? My C++ guts tell me that runner object should be destroyed after RunSomethingASync is finished. Am I right? What happens then to the method running on different thread? Or perhaps it is other way around and runner will not be collected? That would be a problem considering I may call RunSomethingASync() many times.

    Read the article

  • [WPF] The calling thread cannot access this object because a different thread owns it.

    - by zunyite
    Why I can't create CroppedBitmap in the following code ? I got an exception : The calling thread cannot access this object because a different thread owns it. public MainWindow() { InitializeComponent(); ThreadPool.QueueUserWorkItem((o) => { //load a large image file var bf = BitmapFrame.Create( new Uri("D:\\1172735642.jpg"), BitmapCreateOptions.DelayCreation | BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.None); bf.Freeze(); Dispatcher.BeginInvoke( new Action(() => { CroppedBitmap cb = new CroppedBitmap(bf, new Int32Rect(1,1,5,5)); cb.Freeze(); //set Image's source to cb.... }), System.Windows.Threading.DispatcherPriority.ApplicationIdle); } ); }

    Read the article

  • Need help understanding .net ThreadPool

    - by Meredith
    I am trying to understand what ThreadPool does, I have this .NET example: class Program { static void Main() { int c = 2; // Use AutoResetEvent for thread management AutoResetEvent[] arr = new AutoResetEvent[50]; for (int i = 0; i < arr.Length; ++i) { arr[i] = new AutoResetEvent(false); } // Set the number of minimum threads ThreadPool.SetMinThreads(c, 4); // Enqueue 50 work items that run the code in this delegate function for (int i = 0; i < arr.Length; i++) { ThreadPool.QueueUserWorkItem(delegate(object o) { Thread.Sleep(100); arr[(int)o].Set(); // Signals completion }, i); } // Wait for all tasks to complete WaitHandle.WaitAll(arr); } } Does this run 50 "tasks", in groups of 2 (int c) until they all finish? Or I am not understanding what it really does.

    Read the article

  • Lock thread using somthing other than a object

    - by Scott Chamberlain
    when using a lock does the thing you are locking on have to be a object. For example is this legal static DateTime NextCleanup = DateTime.Now; const TimeSpan CleanupInterval = new TimeSpan(1, 0, 0); private static void DoCleanup() { lock ((object)NextCleanup) { if (NextCleanup < DateTime.Now) { NextCleanup = DateTime.Now.Add(CleanupInterval); System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(cleanupThread)); } } return; } EDIT-- From reading SLaks' responce I know the above code would be not valid but would this be? static MyClass myClass = new MyClass(); private static void DoCleanup() { lock (myClass) { // } return; }

    Read the article

  • C# Express 2010 Multi-Threading

    - by Chris Evans
    Hi, I have a windows app that I have been running in c# Express 2008 for a year and have been trying to convert it over the last few days to 2010. The problem I am having is it is a multi-threaded application that has to run a series of code every second. What it does is have a main thread, that calls 3 worker threads, waits for them to finish then does some additional processing, sleeps till 1 second and runs again. The problem is part of the code can call a web service that takes 8 seconds to respond, so this bit of code gets called using ThreadPool.QueueUserWorkItem. The problem is when running in 2010 when this part of the code gets called the main thread continues to run but when it awakens the sub threads it hangs until the Threadpool method finishes running. This never happens in 2008. Any suggestions? So far I put that bit of code in it's own thread rather than using Threadpool but same issue.

    Read the article

  • Running a ProgressDialog MonoAndroid

    - by user1791926
    I am trying to run a progressDialog that will loading items into a Sqlite datebase on a first load for my application. I get an error message because the application runs the rest of the code in the application before the rest of the data is loaded into the database. How do I make sure the code is completed in the progressDialog before the code in the rest of the program? LocalDatabase DB = new LocalDatabase(); var dbpd = ProgressDialog.Show(this, "Loading Database", "Please wait Loading Data",true); ThreadPool.QueueUserWorkItem((s) =>{ DB.createDB(); RunOnUiThread(() => databaseLoaded()); });

    Read the article

  • Dynamically load and call delegates based on source data

    - by makerofthings7
    Assume I have a stream of records that need to have some computation. Records will have a combination of these functions run Sum, Aggregate, Sum over the last 90 seconds, or ignore. A data record looks like this: Date;Data;ID Question Assuming that ID is an int of some kind, and that int corresponds to a matrix of some delegates to run, how should I use C# to dynamically build that launch map? I'm sure this idea exists... it is used in Windows Forms which has many delegates/events, most of which will never actually be invoked in a real application. The sample below includes a few delegates I want to run (sum, count, and print) but I don't know how to make the quantity of delegates fire based on the source data. (say print the evens, and sum the odds in this sample) using System; using System.Threading; using System.Collections.Generic; internal static class TestThreadpool { delegate int TestDelegate(int parameter); private static void Main() { try { // this approach works is void is returned. //ThreadPool.QueueUserWorkItem(new WaitCallback(PrintOut), "Hello"); int c = 0; int w = 0; ThreadPool.GetMaxThreads(out w, out c); bool rrr =ThreadPool.SetMinThreads(w, c); Console.WriteLine(rrr); // perhaps the above needs time to set up6 Thread.Sleep(1000); DateTime ttt = DateTime.UtcNow; TestDelegate d = new TestDelegate(PrintOut); List<IAsyncResult> arDict = new List<IAsyncResult>(); int count = 1000000; for (int i = 0; i < count; i++) { IAsyncResult ar = d.BeginInvoke(i, new AsyncCallback(Callback), d); arDict.Add(ar); } for (int i = 0; i < count; i++) { int result = d.EndInvoke(arDict[i]); } // Give the callback time to execute - otherwise the app // may terminate before it is called //Thread.Sleep(1000); var res = DateTime.UtcNow - ttt; Console.WriteLine("Main program done----- Total time --> " + res.TotalMilliseconds); } catch (Exception e) { Console.WriteLine(e); } Console.ReadKey(true); } static int PrintOut(int parameter) { // Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Delegate PRINTOUT waited and printed this:"+parameter); var tmp = parameter * parameter; return tmp; } static int Sum(int parameter) { Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread return parameter; } static int Count(int parameter) { Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread return parameter; } static void Callback(IAsyncResult ar) { TestDelegate d = (TestDelegate)ar.AsyncState; //Console.WriteLine("Callback is delayed and returned") ;//d.EndInvoke(ar)); } }

    Read the article

  • Entity Framework lazy loading doesn't work from other thread

    - by Thomas Levesque
    Hi, I just found out that lazy loading in Entity Framework only works from the thread that created the ObjectContext. To illustrate the problem, I did a simple test, with a simple model containing just 2 entities : Person and Address. Here's the code : private static void TestSingleThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Console.WriteLine("{0} lives in {1}.", p.Name, p.Address.City); } } } private static void TestMultiThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Person p2 = p; // to avoid capturing the loop variable ThreadPool.QueueUserWorkItem( arg => { Console.WriteLine("{0} lives in {1}.", p2.Name, p2.Address.City); }); } } } The TestSingleThread method works fine, the Address property is lazily loaded. But in TestMultiThread, I get a NullReferenceException on p2.Address.City, because p2.Address is null. It that a bug ? Is this the way it's supposed to work ? If so, is there any documentation mentioning it ? I couldn't find anything on the subject on MSDN or Google... And more importantly, is there a workaround ? (other than explicitly calling LoadProperty from the worker thread...) Any help would be very appreciated PS: I'm using VS2010, so it's EF 4.0. I don't know if it was the same in the previous version of EF...

    Read the article

  • How to log correct context with Threadpool threads using log4net?

    - by myotherme
    I am trying to find a way to log useful context from a bunch of threads. The problem is that a lot of code is dealt with on Events that are arriving via threadpool threads (as far as I can tell) so their names are not in relation to any context. The problem can be demonstrated with the following code: class Program { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); static void Main(string[] args) { new Thread(TestThis).Start("ThreadA"); new Thread(TestThis).Start("ThreadB"); Console.ReadLine(); } private static void TestThis(object name) { var nameStr = (string)name; Thread.CurrentThread.Name = nameStr; log4net.ThreadContext.Properties["ThreadContext"] = nameStr; log4net.LogicalThreadContext.Properties["LogicalThreadContext"] = nameStr; log.Debug("From Thread itself"); ThreadPool.QueueUserWorkItem(x => log.Debug("From threadpool Thread: " + nameStr)); } } The Conversion pattern is: %date [%thread] %-5level %logger [%property] - %message%newline The output is like so: 2010-05-21 15:08:02,357 [ThreadA] DEBUG LogicalContextTest.Program [{LogicalThreadContext=ThreadA, log4net:HostName=xxx, ThreadContext=ThreadA}] - From Thread itself 2010-05-21 15:08:02,357 [ThreadB] DEBUG LogicalContextTest.Program [{LogicalThreadContext=ThreadB, log4net:HostName=xxx, ThreadContext=ThreadB}] - From Thread itself 2010-05-21 15:08:02,404 [7] DEBUG LogicalContextTest.Program [{log4net:HostName=xxx}] - From threadpool Thread: ThreadA 2010-05-21 15:08:02,420 [16] DEBUG LogicalContextTest.Program [{log4net:HostName=xxx}] - From threadpool Thread: ThreadB As you can see the last two rows have no Names of useful information to distinguish the 2 threads, other than manually adding the name to the message (which I want to avoid). How can I get the Name/Context into the log for the threadpool threads without adding it to the message at every call?

    Read the article

  • Using CallExternalMethodActivity/HandleExternalEventActivity in StateMachine

    - by AngrySpade
    I'm attempting to make a StateMachine execute some database action between states. So I have a "starting" state that uses CallExternalMethodActivity to call a "BeginExecuteNonQuery" function on an class decorated with ExternalDataExchangeAttribute. After that it uses a SetStateActivity to change to an "ending" state. The "ending" state uses a HandleExternalEventActivity to listen to a "EndExecuteNonQuery" event. I can step through the local service, into the "BeginExecuteNonQuery" function. The problem is that the "EndExecuteNonQuery" is null. public class FailoverWorkflowController : IFailoverWorkflowController { private readonly WorkflowRuntime workflowRuntime; private readonly FailoverWorkflowControlService failoverWorkflowControlService; private readonly DatabaseControlService databaseControlService; public FailoverWorkflowController() { workflowRuntime = new WorkflowRuntime(); workflowRuntime.WorkflowCompleted += workflowRuntime_WorkflowCompleted; workflowRuntime.WorkflowTerminated += workflowRuntime_WorkflowTerminated; ExternalDataExchangeService dataExchangeService = new ExternalDataExchangeService(); workflowRuntime.AddService(dataExchangeService); databaseControlService = new DatabaseControlService(); workflowRuntime.AddService(databaseControlService); workflowRuntime.StartRuntime(); } ... } ... public void BeginExecuteNonQuery(string command) { Guid workflowInstanceID = WorkflowEnvironment.WorkflowInstanceId; ThreadPool.QueueUserWorkItem(delegate(object state) { try { int result = ExecuteNonQuery((string)state); EndExecuteNonQuery(null, new ExecuteNonQueryResultEventArgs(workflowInstanceID, result)); } catch (Exception exception) { EndExecuteNonQuery(null, new ExecuteNonQueryResultEventArgs(workflowInstanceID, exception)); } }, command); } What am I doing wrong with my implementation? -Stan

    Read the article

  • How to know if all the Thread Pool's thread are already done with its tasks?

    - by mcxiand
    I have this application that will recurse all folders in a given directory and look for PDF. If a PDF file is found, the application will count its pages using ITextSharp. I did this by using a thread to recursively scan all the folders for pdf, then if then PDF is found, this will be queued to the thread pool. The code looks like this: //spawn a thread to handle the processing of pdf on each folder. var th = new Thread(() => { pdfDirectories = Directory.GetDirectories(pdfPath); processDir(pdfDirectories); }); th.Start(); private void processDir(string[] dirs) { foreach (var dir in dirs) { pdfFiles = Directory.GetFiles(dir, "*.pdf"); processFiles(pdfFiles); string[] newdir = Directory.GetDirectories(dir); processDir(newdir); } } private void processFiles(string[] files) { foreach (var pdf in files) { ThreadPoolHelper.QueueUserWorkItem( new { path = pdf }, (data) => { processPDF(data.path); } ); } } My problem is, how do i know that the thread pool's thread has finished processing all the queued items so i can tell the user that the application is done with its intended task?

    Read the article

  • multi-threaded proxy checker having problems

    - by Paul
    hello everyone, I am trying to create a proxy checker. This is my first attempt at multithreading and it's not going so well, the threads seem to be waiting for one to complete before initializing the next. Imports System.Net Imports System.IO Imports System.Threading Public Class Form1 Public sFileName As String Public srFileReader As System.IO.StreamReader Public sInputLine As String Public Class WebCall Public proxy As String Public htmlout As String Public Sub New(ByVal proxy As String) Me.proxy = proxy End Sub Public Event ThreadComplete(ByVal htmlout As String) Public Sub send() Dim myWebRequest As HttpWebRequest = CType(WebRequest.Create("http://www.myserver.com/ip.php"), HttpWebRequest) myWebRequest.Proxy = New WebProxy(proxy, False) Try Dim myWebResponse As HttpWebResponse = CType(myWebRequest.GetResponse(), HttpWebResponse) Dim loResponseStream As StreamReader = New StreamReader(myWebResponse.GetResponseStream()) htmlout = loResponseStream.ReadToEnd() Debug.WriteLine("Finished - " & htmlout) RaiseEvent ThreadComplete(htmlout) Catch ex As WebException If (ex.Status = WebExceptionStatus.ConnectFailure) Then End If Debug.WriteLine("Failed - " & proxy) End Try End Sub End Class Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim proxy As String Dim webArray As New ArrayList() Dim n As Integer For n = 0 To 2 proxy = srFileReader.ReadLine() webArray.Add(New WebCall(proxy)) Next Dim w As WebCall For Each w In webArray Threading.ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf w.send), w) Next w End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load srFileReader = System.IO.File.OpenText("proxies.txt") End Sub End Class

    Read the article

  • C# Process Binary File, Multi-Thread Processing

    - by washtik
    I have the following code that processes a binary file. I want to split the processing workload by using threads and assigning each line of the binary file to threads in the ThreadPool. Processing time for each line is only small but when dealing with files that might contain hundreds of lines, it makes sense to split the workload. My question is regarding the BinaryReader and thread safety. First of all, is what I am doing below acceptable. I have a feeling it would be better to pass only the binary for each line to the PROCESS_Binary_Return_lineData method. Please note the code below is conceptual. I looking for a but of guidance on this as my knowledge of multi-threading is in its infancy. Perhaps there is a better way to achieve the same result, i.e. split processing of each binary line. var dic = new Dictionary<DateTime, Data>(); var resetEvent = new ManualResetEvent(false); using (var b = new BinaryReader(File.Open(Constants.dataFile, FileMode.Open, FileAccess.Read, FileShare.Read))) { var lByte = b.BaseStream.Length; var toProcess = 0; while (lByte >= DATALENGTH) { b.BaseStream.Position = lByte; lByte = lByte - AB_DATALENGTH; ThreadPool.QueueUserWorkItem(delegate { Interlocked.Increment(ref toProcess); var lineData = PROCESS_Binary_Return_lineData(b); lock(dic) { if (!dic.ContainsKey(lineData.DateTime)) { dic.Add(lineData.DateTime, lineData); } } if (Interlocked.Decrement(ref toProcess) == 0) resetEvent.Set(); }, null); } } resetEvent.WaitOne();

    Read the article

  • How to: generate UnhandledException?

    - by serhio
    I use this code to catch the WinForm application UnhandledException. [STAThread] static void Main(string[] args) { // Add the event handler for handling UI thread exceptions to the event. Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); // Set the unhandled exception mode to force all Windows Forms errors // to go through our handler. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // Add the event handler for handling non-UI thread exceptions to the event. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); try { Application.Run(new MainForm()); } catch.... There I will try to restart the application. Now my problem is to simulate a exception like this. I tried before try (in main): throw new NullReferenceException("test"); VS caught it. Tried also in MainForm code with button : private void button1_Click(object sender, EventArgs ev) { ThreadPool.QueueUserWorkItem(new WaitCallback(TestMe), null); } protected void TestMe(object state) { string s = state.ToString(); } did not help, VS caught it, even in Release mode. How should I, finally, force the application generate UnhandleldException? Will I be able to restart the application in CurrentDomain_UnhandledException?

    Read the article

  • ASP.NET CacheDependency out of ThreadPool

    - by Stephen
    In an async http handler, we add items to the ASP.NET cache, with dependencies on some files. If the async method executes on a thread from the ThreadPool, all is fine: AsyncResult result = new AsyncResult(context, cb, extraData); ThreadPool.QueueUserWorkItem(new WaitCallBack(DoProcessRequest), result); But as soon as we try to execute on a thread out of the ThreadPool: AsyncResult result = new AsyncResult(context, cb, extraData); Runner runner = new Runner(result); Thread thread = new Thread(new ThreadStart(runner.Run()); ... where Runner.Run just invokes DoProcessRequest, The dependencies do trigger right after the thread exits. I.e. the items are immediately removed from the cache, the reason being the dependencies. We want to use an out-of-pool thread because the processing might take a long time. So obviously something's missing when we create the thread. We might need to propagate the call context, the http context... Has anybody already encountered that issue? Note: off-the-shelf custom threadpools probably solve this. Writing our own threadpool is probably a bad idea (think NIH syndrom). Yet I'd like to understand this in details, though.

    Read the article

  • Port scanning using threadpool

    - by thenry
    I am trying to run a small app that scans ports and checks to see if they are open using and practicing with threadpools. The console window will ask a number and scans ports from 1 to X and will display each port whether they are open or closed. My problem is that as it goes through each port, it sometimes stops prematurely. It doesn't stop at just one number either, its pretty random. For example it I specify 200. The console will scroll through each port then stops at 110. Next time I run it, it stops at 80. Code Left out some of the things, assume all variables are declared where they should. First part is in Main. static void Main(string[] args) { string portNum; int convertedNum; Console.WriteLine("Scanning ports 1-X"); portNum = Console.ReadLine(); convertedNum = Convert.ToInt32(portNum); try { for (int i = 1; i <= convertedNum; i++) { ThreadPool.QueueUserWorkItem(scanPort, i); Thread.Sleep(100); } } catch (Exception e) { Console.WriteLine("exception " + e); } } static void scanPort(object o) { TcpClient scanner = new TcpClient(); try { scanner.Connect("127.0.0.1",(int)o); Console.WriteLine("Port {0} open", o); } catch { Console.WriteLine("Port {0} closed",o); } } }

    Read the article

  • Why I can't get all UDP packets?

    - by Jack
    My program use UdpClient to try to receive 27 responses from 27 hosts. The size of the response is 10KB. My broadband incoming bandwidth is 150KB/s. The 27 responses are sent from the hosts almost at the same time and for every 10 secs. However, I can only receive 8 - 17 responses each time. The number of responses that I can receive is quite dynamic but within the range. Can anyone tell me why? why can't I receive all? I understand UDP is not reliable. but I tried receiving 5 - 10 responses at the same time, it worked. I guess the network links are not so bad. The code is very simple. ON the 27 hosts, I just use UdpClient to send 10KB to my machine. On my machine, I have one UdpClient receive datagrams. Each time I get a data, I create a thread to handle it (basically handling it means just print out "I received 10KB", but it runs in a thread). listener = new UDPListener(Port); listener.Start(); while (true) { try { UDPContext context = listener.Accept(); ThreadPool.QueueUserWorkItem(new WaitCallback(HandleMessage), context); } catch (Exception) { } } If I reduce the size of the response down to 3KB, the case gets much better that roughly 25 responses can be received. Any more idea? UDP buffer problems???

    Read the article

  • .NET 4 ... Parallel.ForEach() question

    - by CirrusFlyer
    I understand that the new TPL (Task Parallel Library) has implemented the Parallel.ForEach() such that it works with "expressed parallelism." Meaning, it does not guarantee that your delegates will run in multiple threads, but rather it checks to see if the host platform has multiple cores, and if true, only then does it distribute the work across the cores (essentially 1 thread per core). If the host system does not have multiple cores (getting harder and harder to find such a computer) then it will run your code sequenceally like a "regular" foreach loop would. Pretty cool stuff, frankly. Normally I would do something like the following to place my long running operation on a background thread from the ThreadPool: ThreadPool.QueueUserWorkItem( new WaitCallback(targetMethod), new Object2PassIn() ); In a situation whereby the host computer only has a single core does the TPL's Parallel.ForEach() automatically place the invocation on a background thread? Or, should I manaully invoke any TPL calls from a background thead so that if I am executing from a single core computer at least that logic will be off of the GUI's dispatching thread? My concern is if I leave the TPL in charge of all this I want to ensure if it determines it's a single core box that it still marshalls the code that's inside of the Parallel.ForEach() loop on to a background thread like I would have done, so as to not block my GUI. Thanks for any thoughts or advice you may have ...

    Read the article

< Previous Page | 1 2 3  | Next Page >