Search Results

Search found 40 results on 2 pages for 'waithandle'.

Page 1/2 | 1 2  | Next Page >

  • Workaround for the WaitHandle.WaitAll 64 handle limit?

    - by James
    My application spawns loads of different small worker threads via ThreadPool.QueueUserWorkItem. I have never had any issues before, however, as my application is coming under more load i.e. more threads being created, I am now beginning to get this exception: WaitHandles must be less than or equal to 64 - missing documentation What is the best alternative solution to this?

    Read the article

  • How-to dispose a waithandle correctly

    - by TomTom
    Hello, I'm doing some multi-threading and use AutoResetEvents and ManualResetEvents do control my main - loop. When "destryoing" the threads I also have to dispose these signals, that's clear. But I saw different ways how to dispose Waithandles, and I'm not sure which one is correct: Version 1 if (disposing) { this.threadExitEvent.SafeWaitHandle.Dispose(); this.threadExitEvent.Close(); this.threadExitEvent = null; .... } Version 2 if (disposing) { this.threadExitEvent.Close(); this.threadExitEvent = null; .... } Version 3 if (disposing) { this.threadExitEvent.Close(); .... }

    Read the article

  • Can a call to WaitHandle.SignalAndWait be ignored for performance profiling purposes?

    - by Dan Tao
    I just downloaded the trial version of ANTS Performance Profiler from Red Gate and am investigating some of my team's code. Immediately I notice that there's a particular section of code that ANTS is reporting as eating up to 99% CPU time. I am completely unfamiliar with ANTS or performance profiling in general (that is, aside from self-profiling using what I'm sure are extremely crude and frowned-upon methods such as double timeToComplete = (endTime - startTime).TotalSeconds), so I'm still fiddling around with the application and figuring out how it's used. But I did call the developer responsible for the code in question and his immediate reaction was "Yeah, that doesn't surprise me that it says that; but that code calls SignalAndWait [which I could see for myself, thanks to ANTS], which doesn't use any CPU, it just sits there waiting for something to do." He advised me to simply ignore that code and look for anything ELSE I could find. My question: is it true that SignalAndWait requires NO CPU overhead (and if so, how is this possible?), and is it reasonable that a performance profiler would view it as taking up 99% CPU time? I find this particularly curious because, if it's at 99%, that would suggest that our application is often idle, wouldn't it? And yet its performance has become rather sluggish lately. Like I said, I really am just a beginner when it comes to this tool, and I don't know anything about the WaitHandle class. So ANY information to help me to understand what's going on here would be appreciated.

    Read the article

  • reading txt storing in different

    - by dev2
    ASp.NET application. In button click i am accessing one text file and reading content and storing in other destination. while both users clicking this button at a time deadlock(thread is being used by other process) will occurs so how to handle this i want to read each user one by one can any one suggest method to handle. i am looking to handle with waithandle events so can any one give a code sample for above scenario.

    Read the article

  • Why doesn't my NamedPipeServerStream wait??

    - by Frank Fella
    I'm working with a NamedPipeServerStream to communicate between two processes. Here is the code where I initialize and connect the pipe: void Foo(IHasData objectProvider) { Stream stream = objectProvider.GetData(); if (stream.Length > 0) { using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("VisualizerPipe", PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { string currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string uiFileName = Path.Combine(currentDirectory, "VisualizerUIApplication.exe"); Process.Start(uiFileName); if(pipeServer.BeginWaitForConnection(PipeConnected, this).AsyncWaitHandle.WaitOne(5000)) { while (stream.CanRead) { pipeServer.WriteByte((byte)stream.ReadByte()); } } else { throw new TimeoutException("Pipe connection to UI process timed out."); } } } } private void PipeConnected(IAsyncResult e) { } But it never seems to wait. I constantly get the following exception: System.InvalidOperationException: Pipe hasn't been connected yet. at System.IO.Pipes.PipeStream.CheckWriteOperations() at System.IO.Pipes.PipeStream.WriteByte(Byte value) at PeachesObjectVisualizer.Visualizer.Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider) I would think that after the wait returns everything should be ready to go. If I use pipeServer.WaitForConnection() everything works fine, but hanging the application if the pipe doesn't connect is not an option.

    Read the article

  • C#: How to set AsyncWaitHandle in Compact Framework?

    - by Thorsten Dittmar
    Hi, I'm using a TcpClient in one of my Compact Framework 2.0 applications. I want to receive some information from a TCP server. As the Compact Framework does not support the timeout mechanisms of the "large" framework, I'm trying to implement my own timeout-thing. Basically, I want to do the following: IAsyncResult result = client.BeginRead(buffer, 0, size, ..., stream); if (!result.AsyncWaitHandle.WaitOne(5000, false)) // Handle timeout private void ReceiveFinished(IAsyncResult ar) { NetworkStream stream = (NetworkStream)ar.AsyncState; int numBytes = stream.EndRead(ar); // SIGNAL IASYNCRESULT.ASYNCWAITHANDLE HERE ... HOW?? } I'd like to call Set for the IAsyncResult.AsyncWaitHandle, but it doesn't have such a method and I don't know which implementation to cast it to. How do I set the wait handle? Or is it automatically set by calling EndRead? The documentation suggests that I'd have to call Set myself... Thanks for any help!

    Read the article

  • What is the difference between Thread.Sleep(timeout) and ManualResetEvent.Wait(timeout)?

    - by Erik Forbes
    Both Thread.Sleep(timeout) and resetEvent.Wait(timeout) cause execution to pause for at least timeout milliseconds, so is there a difference between them? I know that Thread.Sleep causes the thread to give up the remainder of its time slice, thus possibly resulting in a sleep that lasts far longer than asked for. Does the Wait(timeout) method of a ManualResetEvent object have the same problem?

    Read the article

  • How do you prevent IDisposable from spreading to all your classes?

    - by GrahamS
    Start with these simple classes... Let's say I have a simple set of classes like this: class Bus { Driver busDriver = new Driver(); } class Driver { Shoe[] shoes = { new Shoe(), new Shoe() }; } class Shoe { Shoelace lace = new Shoelace(); } class Shoelace { bool tied = false; } A Bus has a Driver, the Driver has two Shoes, each Shoe has a Shoelace. All very silly. Add an IDisposable object to Shoelace Later I decide that some operation on the Shoelace could be multi-threaded, so I add an EventWaitHandle for the threads to communicate with. So Shoelace now looks like this: class Shoelace { private AutoResetEvent waitHandle = new AutoResetEvent(false); bool tied = false; // ... other stuff .. } Implement IDisposable on Shoelace Buit now FxCop will complain: "Implement IDisposable on 'Shoelace' because it creates members of the following IDisposable types: 'EventWaitHandle'." Okay, I implement IDisposable on Shoelace and my neat little class becomes this horrible mess: class Shoelace : IDisposable { private AutoResetEvent waitHandle = new AutoResetEvent(false); bool tied = false; private bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Shoelace() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (waitHandle != null) { waitHandle.Close(); waitHandle = null; } } // No unmanaged resources to release otherwise they'd go here. } disposed = true; } } Or (as pointed out by commenters) since Shoelace itself has no unmanaged resources, I might use the simpler dispose implementation without needing the Dispose(bool) and Destructor: class Shoelace : IDisposable { private AutoResetEvent waitHandle = new AutoResetEvent(false); bool tied = false; public void Dispose() { if (waitHandle != null) { waitHandle.Close(); waitHandle = null; } GC.SuppressFinalize(this); } } Watch in horror as IDisposable spreads Right that's that fixed. But now FxCop will complain that Shoe creates a Shoelace, so Shoe must be IDisposable too. And Driver creates Shoe so Driver must be IDisposable. and Bus creates Driver so Bus must be IDisposable and so on. Suddenly my small change to Shoelace is causing me a lot of work and my boss is wondering why I need to checkout Bus to make a change to Shoelace. The Question How do you prevent this spread of IDisposable, but still ensure that your unmanaged objects are properly disposed?

    Read the article

  • c# Named Pipe Asynchronous Peeking

    - by KJ Tsanaktsidis
    Hey all, I need to find a way to be notified when a System.IO.Pipe.NamedPipeServerStream opened in asynchronous mode has more data available for reading on it- a WaitHandle would be ideal. I cannot simply use BeginRead() to obtain such a handle because it's possible that i might be signaled by another thread which wants to write to the pipe- so I have to release the lock on the pipe and wait for the write to be complete, and NamedPipeServerStream doesnt have a CancelAsync method. I also tried calling BeginRead(), then calling the win32 function CancelIO on the pipe if the thread gets signaled, but I don't think this is an ideal solution because if CancelIO is called just as data is arriving and being processed, it will be dropped- I still wish to keep this data, but process it at a later time, after the write. I suspect the win32 function PeekNamedPipe might be useful but i'd like to avoid having to continuously poll for new data with it. In the likley event that the above text is a bit unclear, here's roughly what i'd like to be able to do... NamedPipeServerStream pipe; ManualResetEvent WriteFlag; //initialise pipe lock (pipe) { //I wish this method existed WaitHandle NewDataHandle = pipe.GetDataAvailableWaithandle(); Waithandle[] BreakConditions = new Waithandle[2]; BreakConditions[0] = NewDataHandle; BreakConditions[1] = WriteFlag; int breakcode = WaitHandle.WaitAny(BreakConditions); switch (breakcode) { case 0: //do a read on the pipe break; case 1: //break so that we release the lock on the pipe break; } }

    Read the article

  • C# powershell output reader iterator getting modified when pipeline closed and disposed.

    - by scope-creep
    Hello, I'm calling a powershell script from C#. The script is pretty small and is "gps;$host.SetShouldExit(9)", which list process, and then send back an exit code to be captured by the PSHost object. The problem I have is when the pipeline has been stopped and disposed, the output reader PSHost collection still seems to be written to, and is filling up. So when I try and copy it to my own output object, it craps out with a OutOfMemoryException when I try to iterate over it. Sometimes it will except with a Collection was modified message. Here is the code. private void ProcessAndExecuteBlock(ScriptBlock Block) { Collection<PSObject> PSCollection = new Collection<PSObject>(); Collection<Object> PSErrorCollection = new Collection<Object>(); Boolean Error = false; int ExitCode=0; //Send for exection. ExecuteScript(Block.Script); // Process the waithandles. while (PExecutor.PLine.PipelineStateInfo.State == PipelineState.Running) { // Wait for either error or data waithandle. switch (WaitHandle.WaitAny(PExecutor.Hand)) { // Data case 0: Collection<PSObject> data = PExecutor.PLine.Output.NonBlockingRead(); if (data.Count > 0) { for (int cnt = 0; cnt <= (data.Count-1); cnt++) { PSCollection.Add(data[cnt]); } } // Check to see if the pipeline has been closed. if (PExecutor.PLine.Output.EndOfPipeline) { // Bring back the exit code. ExitCode = RHost.ExitCode; } break; case 1: Collection<object> Errordata = PExecutor.PLine.Error.NonBlockingRead(); if (Errordata.Count > 0) { Error = true; for (int count = 0; count <= (Errordata.Count - 1); count++) { PSErrorCollection.Add(Errordata[count]); } } break; } } PExecutor.Stop(); // Create the Execution Return block ExecutionResults ER = new ExecutionResults(Block.RuleGuid,Block.SubRuleGuid, Block.MessageIdentfier); ER.ExitCode = ExitCode; // Add in the data results. lock (ReadSync) { if (PSCollection.Count > 0) { ER.DataAdd(PSCollection); } } // Add in the error data if any. if (Error) { if (PSErrorCollection.Count > 0) { ER.ErrorAdd(PSErrorCollection); } else { ER.InError = true; } } // We have finished, so enque the block back. EnQueueOutput(ER); } and this is the PipelineExecutor class which setups the pipeline for execution. public class PipelineExecutor { private Pipeline pipeline; private WaitHandle[] Handles; public Pipeline PLine { get { return pipeline; } } public WaitHandle[] Hand { get { return Handles; } } public PipelineExecutor(Runspace runSpace, string command) { pipeline = runSpace.CreatePipeline(command); Handles = new WaitHandle[2]; Handles[0] = pipeline.Output.WaitHandle; Handles[1] = pipeline.Error.WaitHandle; } public void Start() { if (pipeline.PipelineStateInfo.State == PipelineState.NotStarted) { pipeline.Input.Close(); pipeline.InvokeAsync(); } } public void Stop() { pipeline.StopAsync(); } } An this is the DataAdd method, where the exception arises. public void DataAdd(Collection<PSObject> Data) { foreach (PSObject Ps in Data) { Data.Add(Ps); } } I put a for loop around the Data.Add, and the Collection filled up with 600k+ so feels like the gps command is still running, but why. Any ideas. Thanks in advance.

    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

  • Pattern for limiting number of simultaneous asynchronous calls

    - by hitch
    I need to retrieve multiple objects from an external system. The external system supports multiple simultaneous requests (i.e. threads), but it is possible to flood the external system - therefore I want to be able to retrieve multiple objects asynchronously, but I want to be able to throttle the number of simultaneous async requests. i.e. I need to retrieve 100 items, but don't want to be retrieving more than 25 of them at once. When each request of the 25 completes, I want to trigger another retrieval, and once they are all complete I want to return all of the results in the order they were requested (i.e. there is no point returning the results until the entire call is returned). Are there any recommended patterns for this sort of thing? Would something like this be appropriate (pseudocode, obviously)? private List<externalSystemObjects> returnedObjects = new List<externalSystemObjects>; public List<externalSystemObjects> GetObjects(List<string> ids) { int callCount = 0; int maxCallCount = 25; WaitHandle[] handles; foreach(id in itemIds to get) { if(callCount < maxCallCount) { WaitHandle handle = executeCall(id, callback); addWaitHandleToWaitArray(handle) } else { int returnedCallId = WaitHandle.WaitAny(handles); removeReturnedCallFromWaitHandles(handles); } } WaitHandle.WaitAll(handles); return returnedObjects; } public void callback(object result) { returnedObjects.Add(result); }

    Read the article

  • Gnome Do not Launching

    - by PyRulez
    When I try running gnome do, I get this. chris@Chris-Ubuntu-Laptop:~$ gnome-do pgrep: invalid user name: -u and it is not writable Trying sudo: chris@Chris-Ubuntu-Laptop:~$ sudo gnome-do [NetworkService] Could not initialize Network Manager dbus: Unable to open the session message bus. [Error 17:54:30.122] [SystemService] Could not initialize dbus: Unable to open the session message bus. (Do:2401): Wnck-CRITICAL **: wnck_set_client_type got called multiple times. (Do:2401): libdo-WARNING **: Binding '<Super>space' failed! [Error 17:54:30.649] [AbstractKeyBindingService] Key "" is already mapped. Tomboy.NotesItemSource "Tomboy Notes" encountered an error in UpdateItems: System.TypeInitializationException: An exception was thrown by the type initializer for Tomboy.TomboyDBus ---> System.Exception: Unable to open the session message bus. ---> System.ArgumentNullException: Argument cannot be null. Parameter name: address at NDesk.DBus.Bus.Open (System.String address) [0x00000] in <filename unknown>:0 at NDesk.DBus.Bus.get_Session () [0x00000] in <filename unknown>:0 --- End of inner exception stack trace --- at NDesk.DBus.Bus.get_Session () [0x00000] in <filename unknown>:0 at Tomboy.TomboyDBus..cctor () [0x00000] in <filename unknown>:0 --- End of inner exception stack trace --- at Tomboy.NotesItemSource.UpdateItems () [0x00000] in <filename unknown>:0 at Do.Universe.Safe.SafeItemSource.UpdateItems () [0x00000] in <filename unknown>:0 . Firefox.PlacesItemSource "Firefox Places" encountered an error in UpdateItems: System.InvalidCastException: Cannot cast from source type to destination type. at Mono.Data.Sqlite.SqliteDataReader.VerifyType (Int32 i, DbType typ) [0x00000] in <filename unknown>:0 at Mono.Data.Sqlite.SqliteDataReader.GetString (Int32 i) [0x00000] in <filename unknown>:0 at Firefox.PlacesItemSource+<LoadPlaceItems>c__Iterator3.MoveNext () [0x00000] in <filename unknown>:0 at System.Collections.Generic.List`1[Firefox.PlaceItem].AddEnumerable (IEnumerable`1 enumerable) [0x00000] in <filename unknown>:0 at System.Collections.Generic.List`1[Firefox.PlaceItem]..ctor (IEnumerable`1 collection) [0x00000] in <filename unknown>:0 at System.Linq.Enumerable.ToArray[PlaceItem] (IEnumerable`1 source) [0x00000] in <filename unknown>:0 at Firefox.PlacesItemSource.UpdateItems () [0x00000] in <filename unknown>:0 at Do.Universe.Safe.SafeItemSource.UpdateItems () [0x00000] in <filename unknown>:0 . Do.Universe.Linux.GNOMESpecialLocationsItemSource "GNOME Special Locations" encountered an error in UpdateItems: System.IO.FileNotFoundException: Could not find file "/root/.gtk-bookmarks". File name: '/root/.gtk-bookmarks' at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in <filename unknown>:0 at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share) [0x00000] in <filename unknown>:0 at (wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare) at System.IO.File.OpenRead (System.String path) [0x00000] in <filename unknown>:0 at System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) [0x00000] in <filename unknown>:0 at System.IO.StreamReader..ctor (System.String path) [0x00000] in <filename unknown>:0 at (wrapper remoting-invoke-with-check) System.IO.StreamReader:.ctor (string) at Do.Universe.Linux.GNOMESpecialLocationsItemSource+<ReadBookmarkItems>c__Iterator3.MoveNext () [0x00000] in <filename unknown>:0 at Do.Universe.Linux.GNOMESpecialLocationsItemSource.UpdateItems () [0x00000] in <filename unknown>:0 at Do.Universe.Safe.SafeItemSource.UpdateItems () [0x00000] in <filename unknown>:0 . ^[^\Full thread dump: "<unnamed thread>" tid=0x0xb7570700 this=0x0x56f18 thread handle 0x403 state : not waiting owns () at (wrapper managed-to-native) Mono.Unix.Native.Syscall.read (int,intptr,ulong) <0xffffffff> at Mono.Unix.Native.Syscall.read (int,void*,ulong) <0x00023> at Mono.Unix.UnixStream.Read (byte[],int,int) <0x0008b> at NDesk.DBus.Connection.ReadMessage () <0x0003c> at NDesk.DBus.Connection.Iterate () <0x0001b> at NDesk.DBus.BusG/<Init>c__AnonStorey0.<>m__0 (intptr,NDesk.GLib.IOCondition,intptr) <0x00033> at (wrapper native-to-managed) NDesk.DBus.BusG/<Init>c__AnonStorey0.<>m__0 (intptr,NDesk.GLib.IOCondition,intptr) <0xffffffff> at (wrapper managed-to-native) Gtk.Clipboard.gtk_clipboard_wait_is_text_available (intptr) <0xffffffff> at Gtk.Clipboard.WaitIsTextAvailable () <0x00017> at Do.Universe.SelectedTextItem.UpdateSelection (object,System.EventArgs) <0x00027> at Do.Platform.AbstractApplicationService.OnSummoned () <0x00025> at Do.Platform.ApplicationService.<ApplicationService>m__31 (object,System.EventArgs) <0x00013> at Do.Core.Controller.OnSummoned () <0x00025> at Do.Core.Controller.Summon () <0x00027> at Do.Do.Main (string[]) <0x001eb> at (wrapper runtime-invoke) <Module>.runtime_invoke_void_object (object,intptr,intptr,intptr) <0xffffffff> "<unnamed thread>" tid=0x0xb2c81b40 this=0x0x194150 thread handle 0x412 state : interrupted state owns () at (wrapper managed-to-native) System.IO.InotifyWatcher.ReadFromFD (intptr,byte[],intptr) <0xffffffff> at System.IO.InotifyWatcher.Monitor () <0x0005f> at System.Threading.Thread.StartInternal () <0x00057> at (wrapper runtime-invoke) object.runtime_invoke_void__this__ (object,intptr,intptr,intptr) <0xffffffff> "Universe Update Dispatcher" tid=0x0xb29ffb40 this=0x0x569d8 thread handle 0x41b state : interrupted state owns () at (wrapper managed-to-native) System.Threading.WaitHandle.WaitOne_internal (System.Threading.WaitHandle,intptr,int,bool) <0xffffffff> at System.Threading.WaitHandle.WaitOne (System.TimeSpan,bool) <0x00133> at System.Threading.WaitHandle.WaitOne (System.TimeSpan) <0x00022> at Do.Core.UniverseManager.UniverseUpdateLoop () <0x0007a> at System.Threading.Thread.StartInternal () <0x00057> at (wrapper runtime-invoke) object.runtime_invoke_void__this__ (object,intptr,intptr,intptr) <0xffffffff> Tomboy.NotesItemSource "Tomboy Notes" encountered an error in UpdateItems: System.TypeInitializationException: An exception was thrown by the type initializer for Tomboy.TomboyDBus ---> System.Exception: Unable to open the session message bus. ---> System.ArgumentNullException: Argument cannot be null. Parameter name: address at NDesk.DBus.Bus.Open (System.String address) [0x00000] in <filename unknown>:0 at NDesk.DBus.Bus.get_Session () [0x00000] in <filename unknown>:0 --- End of inner exception stack trace --- at NDesk.DBus.Bus.get_Session () [0x00000] in <filename unknown>:0 at Tomboy.TomboyDBus..cctor () [0x00000] in <filename unknown>:0 --- End of inner exception stack trace --- at Tomboy.NotesItemSource.UpdateItems () [0x00000] in <filename unknown>:0 at Do.Universe.Safe.SafeItemSource.UpdateItems () [0x00000] in <filename unknown>:0 . Firefox.PlacesItemSource "Firefox Places" encountered an error in UpdateItems: System.InvalidCastException: Cannot cast from source type to destination type. at Mono.Data.Sqlite.SqliteDataReader.VerifyType (Int32 i, DbType typ) [0x00000] in <filename unknown>:0 at Mono.Data.Sqlite.SqliteDataReader.GetString (Int32 i) [0x00000] in <filename unknown>:0 at Firefox.PlacesItemSource+<LoadPlaceItems>c__Iterator3.MoveNext () [0x00000] in <filename unknown>:0 at System.Collections.Generic.List`1[Firefox.PlaceItem].AddEnumerable (IEnumerable`1 enumerable) [0x00000] in <filename unknown>:0 at System.Collections.Generic.List`1[Firefox.PlaceItem]..ctor (IEnumerable`1 collection) [0x00000] in <filename unknown>:0 at System.Linq.Enumerable.ToArray[PlaceItem] (IEnumerable`1 source) [0x00000] in <filename unknown>:0 at Firefox.PlacesItemSource.UpdateItems () [0x00000] in <filename unknown>:0 at Do.Universe.Safe.SafeItemSource.UpdateItems () [0x00000] in <filename unknown>:0 . Do.Universe.Linux.GNOMESpecialLocationsItemSource "GNOME Special Locations" encountered an error in UpdateItems: System.IO.FileNotFoundException: Could not find file "/root/.gtk-bookmarks". File name: '/root/.gtk-bookmarks' at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in <filename unknown>:0 at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share) [0x00000] in <filename unknown>:0 at (wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare) at System.IO.File.OpenRead (System.String path) [0x00000] in <filename unknown>:0 at System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) [0x00000] in <filename unknown>:0 at System.IO.StreamReader..ctor (System.String path) [0x00000] in <filename unknown>:0 at (wrapper remoting-invoke-with-check) System.IO.StreamReader:.ctor (string) at Do.Universe.Linux.GNOMESpecialLocationsItemSource+<ReadBookmarkItems>c__Iterator3.MoveNext () [0x00000] in <filename unknown>:0 at Do.Universe.Linux.GNOMESpecialLocationsItemSource.UpdateItems () [0x00000] in <filename unknown>:0 at Do.Universe.Safe.SafeItemSource.UpdateItems () [0x00000] in <filename unknown>:0 . It stops when I try my key combination, ctrl-alt-. It does not pop up though.

    Read the article

  • C# IOException: The process cannot access the file because it is being used by another process.

    - by Michiel Bester
    Hi, I have a slight problem. What my application is supose to do, is to watch a folder for any newly copied file with the extention '.XSD' open the file and assign the lines to an array. After that the data from the array should be inserted into a MySQL database, then move the used file to another folder if it's done. The problem is that the application works fine with the first file, but as soon as the next file is copied to the folder I get this exception for example: 'The process cannot access the file 'C:\inetpub\admission\file2.XPD' because it is being used by another process'. If two files on the onther hand is copied at the same time there's no problem at all. The following code is on the main window: public partial class Form1 : Form { static string folder = specified path; static FileProcessor processor; public Form1() { InitializeComponent(); processor = new FileProcessor(); InitializeWatcher(); } static FileSystemWatcher watcher; static void InitializeWatcher() { watcher = new FileSystemWatcher(); watcher.Path = folder; watcher.Created += new FileSystemEventHandler(watcher_Created); watcher.EnableRaisingEvents = true; watcher.Filter = "*.XPD"; } static void watcher_Created(object sender, FileSystemEventArgs e) { processor.QueueInput(e.FullPath); } } As you can see the file's path is entered into a queue for processing which is on another class called FileProcessor: class FileProcessor { private Queue<string> workQueue; private Thread workerThread; private EventWaitHandle waitHandle; public FileProcessor() { workQueue = new Queue<string>(); waitHandle = new AutoResetEvent(true); } public void QueueInput(string filepath) { workQueue.Enqueue(filepath); if (workerThread == null) { workerThread = new Thread(new ThreadStart(Work)); workerThread.Start(); } else if (workerThread.ThreadState == ThreadState.WaitSleepJoin) { waitHandle.Set(); } } private void Work() { while (true) { string filepath = RetrieveFile(); if (filepath != null) ProcessFile(filepath); else waitHandle.WaitOne(); } } private string RetrieveFile() { if (workQueue.Count > 0) return workQueue.Dequeue(); else return null; } private void ProcessFile(string filepath) { string xName = Path.GetFileName(filepath); string fName = Path.GetFileNameWithoutExtension(filepath); string gfolder = specified path; bool fileInUse = true; string line; string[] itemArray = null; int i = 0; #region Declare Db variables //variables for each field of the database is created here #endregion #region Populate array while (fileInUse == true) { FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader reader = new StreamReader(fs); itemArray = new string[75]; while (!reader.EndOfStream == true) { line = reader.ReadLine(); itemArray[i] = line; i++; } fs.Flush(); reader.Close(); reader.Dispose(); i = 0; fileInUse = false; } #endregion #region Assign Db variables //here all the variables get there values from the array #endregion #region MySql Connection //here the connection to mysql is made and the variables are inserted into the db #endregion #region Test and Move file if (System.IO.File.Exists(gfolder + xName)) { System.IO.File.Delete(gfolder + xName); } Directory.Move(filepath, gfolder + xName); #endregion } } The problem I get occurs in the Populate array region. I read alot of other threads and was lead to believe that by flushing the file stream would help... I am also thinking of adding a try..catch for if the file process was successful, the file is moved to gfolder and if it failed, moved to bfolder Any help would be awesome Tx

    Read the article

  • Can you have too many Delegate.BeginInvoke calls at once?

    - by stewsha
    I am cleaning up some old code converting it to work asynchronously. psDelegate.GetStops decStops = psLoadRetrieve.GetLoadStopsByLoadID; var arStops = decStops.BeginInvoke(loadID, null, null); WaitHandle.WaitAll(new WaitHandle[] { arStops.AsyncWaitHandle }); var stops = decStops.EndInvoke(arStops); Above is a single example of what I am doing for asynchronous work. My plan is to have close to 20 different delegates running. All will call BeginInvoke and wait until they are all complete before calling EndInvoke. My question is will having so many delegates running cause problems? I understand that BeginInvoke uses the ThreadPool to do work and that has a limit of 25 threads. 20 is under that limit but it is very likely that other parts of the system could be using any number of threads from the ThreadPool as well. Thanks!

    Read the article

  • Using ManualResetEvent to wait for multiple Image.ImageOpened events

    - by umlgorithm
    Dictionary<Image, ManualResetEvent> waitHandleMap = new Dictionary<Image, ManualResetEvent>(); List<Image> images = GetImagesWhichAreAlreadyInVisualTree(); foreach (var image in images) { image.Source = new BitmapImage(new Uri("some_valid_image_url")); waitHandleMap.Add(image, new ManualResetEvent(false)); image.ImageOpened += delegate { waitHandleMap[image].Set(); }; image.ImageFailed += delegate { waitHandleMap[image].Set(); }; } WaitHandle.WaitAll(waitHandleMap.Values.ToArray()); WaitHandle.WaitAll blocks the current UI thread, so ImageOpened/ImageFailed events would never get fired. Could you suggest me an easy workaround to wait for the multiple ui events?

    Read the article

  • Is this a clean way to manage AsyncResults with Generic Methods?

    - by Michael Stum
    I've contributed Async Support to a Project I'm using, but I made a bug which I'm trying to fix. Basically I have this construct: private readonly Dictionary<WaitHandle, object> genericCallbacks = new Dictionary<WaitHandle, object>(); public IAsyncResult BeginExecute<T>(RestRequest request, AsyncCallback callback, object state) where T : new() { var genericCallback = new RequestExecuteCaller<T>(this.Execute<T>); var asyncResult = genericCallback.BeginInvoke(request, callback, state); genericCallbacks[asyncResult.AsyncWaitHandle] = genericCallback; return asyncResult; } public RestResponse<T> EndExecute<T>(IAsyncResult asyncResult) where T : new() { var cb = genericCallbacks[asyncResult.AsyncWaitHandle] as RequestExecuteCaller<T>; genericCallbacks.Remove(asyncResult.AsyncWaitHandle); return cb.EndInvoke(asyncResult); } So I have a generic BeginExecute/EndExecute method pair. As I need to store the delegate that is called on EndExecute somewhere I created a dictionary. I'm unsure about using WaitHandles as keys though, but that seems to be the only safe choice. Does this approach make sense? Are WaitHandles unique or could I have two equal ones? Or should I instead use the State (and wrap any user provided state into my own State value)? Just to add, the class itself is non-generic, only the Begin/EndExecute methods are generic.

    Read the article

  • Two questions on ensuring EndInvoke() gets called on a list of IAsyncResult objects

    - by RobV
    So this question is regarding the .Net IAsyncResult design pattern and the necessity of calling EndInvoke as covered in this question Background I have some code where I'm firing off potentially many asynchronous calls to a particular function and then waiting for all these calls to finish before using EndInvoke() to get back all the results. Question 1 I don't know whether any of the calls has encountered an exception until I call EndInvoke() and in the event that an exception occurs in one of the calls the entire method should fail and the exception gets wrapped into an API specific exception and thrown upwards. So my first question is what's the best way then to ensure that the remainder of the async calls get properly terminated? Is a finally block which calls EndInvoke() on the remainder of the unterminated calls (and ignores any further exceptions) the best way to do this? Question 2 Secondly when I first fire off all my asyc calls I then call WaitHandle.WaitAll() on the array of WaitHandle instances that I've got from my IAsyncResult instances. The method which is firing all these async calls has a timeout to adhere to so I provide this to the WaitAll() method. Then I test whether all the calls have completed, if not then the timeout must have been reached so the method should also fail and throw another API specific exception. So my second question is what should I do in this case? I need to call EndInvoke() to terminate all these async calls before I throw the error but at the same time I don't want the code to get stuck since EndInvoke() is blocking. In theory at least if the WaitAll() call times out then all the async calls should themselves have timed out and thrown exceptions (thus completing the call) since they are also governed by a timeout but this timeout is potentially different from the main timeout

    Read the article

  • Can't view database on SQL Server 2008 with domain user

    - by abatishchev
    I created a login for a domain user (domain admin) and added it to role serveradmin, but after logging in I still can't list databases getting next error: The database MyDB is not accessible. (ObjectExplorer) Program Location: at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.DatabaseNavigableItem.get_CanGetChildren() at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItem.GetChildren(IGetChildrenRequest request) at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ExplorerHierarchyNode.BuildChildren(WaitHandle quitEvent) How can I fix that?

    Read the article

  • How to avoid MissingMethodException?

    - by Dimitri C.
    If .NET 3.5 is installed, but not .NET 3.5 SP1, WaitHandle.WaitOne(int) throws a MissingMethodException. I'd like to be notified earlier on if the correct version of the .NET libraries is not available, for example when the application is started. Is this possible? Update: So my question question is twofold: a) How can I determine which version of the .NET library is required by an application? b) How can I determine the currently installed version of the .NET library?

    Read the article

  • accessing one text

    - by dev1
    ASp.NET application. In button click i am accessing one text file and reading content. while both users clicking this button at a time deadlock will occurs so how to handle this i want to read each user one by one can any one suggest method to handle. i am looking to handle with waithandle events so can any one give a code sample for above scenario.

    Read the article

  • Using dispatchertimer in combination with an asynchroneous call

    - by Civelle
    Hi. We have an issue in our Silverlight application which uses WCF and Entity Framework, where we need to trap the event whenever a user shuts down the application by closing the web page or the browser instead of closing the silverlight application. This is in order to verify if any changes have been made, in which case we would ask the user if he wants to save before leaving. We were able to accomplish the part which consists in trapping the closing of the web page: we wrote some code in the application object that have the web page call a method in the silverlight application object. The problem starts when in this method, we do an asynchroneous call to the Web Service to verify if changes have occured (IsDirty). We are using a DispatcherTimer to check for the return of the asynchroneous call. The problem is that the asynchroneous call never completes (in debug mode, it never ends up stepping into the _BfrServ_Customer_IsDirtyCompleted method), while it used to work fine before we added this new functionality. You will find belowthe code we are using. I am new to writing timers in combination with asynchroneous call so I may be doing something wrong but I cannot figure out what. I tried other things also but we without any success.. ====================== CODE ============================================== 'Code in the application object Public Sub New() InitializeComponent() RegisterOnBeforeUnload() _DispatcherTimer.Interval = New TimeSpan(0, 0, 0, 0, 500) End Sub Public Sub RegisterOnBeforeUnload() 'Register Silverlight object for availability in Javascript. Const scriptableObjectName As String = "Bridge" HtmlPage.RegisterScriptableObject(scriptableObjectName, Me) 'Start listening to Javascript event. Dim pluginName As String = HtmlPage.Plugin.Id HtmlPage.Window.Eval(String.Format("window.onbeforeunload = function () {{ var slApp = document.getElementById('{0}'); var result = slApp.Content.{1}.OnBeforeUnload(); if(result.length 0)return result;}}", pluginName, scriptableObjectName)) End Sub Public Function OnBeforeUnload() As String Dim userControls As List(Of UserControl) = New List(Of UserControl) Dim test As Boolean = True If CType(Me.RootVisual, StartPage).LayoutRoot.Children.Item(0).GetType().Name = "MainPage" Then If Not CType(CType(Me.RootVisual, StartPage).LayoutRoot.Children.Item(0), MainPage).FindName("Tab") Is Nothing Then If CType(CType(Me.RootVisual, StartPage).LayoutRoot.Children.Item(0), MainPage).FindName("Tab").Items.Count = 1 Then For Each item As TabItem In CType(CType(Me.RootVisual, StartPage).LayoutRoot.Children.Item(0), MainPage).Tab.Items If item.Content.GetType().Name = "CustomerDetailUI" _Item = item WaitHandle = New AutoResetEvent(False) DoAsyncCall() Exit End If Next End If End If End If If _IsDirty = True Then Return "Do you want to save before leaving." Else Return String.Empty End If End Function Private Sub DoAsyncCall() _Item.Content.CheckForIsDirty(WaitHandle) 'This code resides in the CustomerDetailUI UserControl - see below for the code End Sub Private Sub _DispatcherTimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles _DispatcherTimer.Tick If Not _Item.Content._IsDirtyCompleted = True Then Exit Sub End If _DispatcherTimerRunning = False _DispatcherTimer.Stop() ProcessAsyncCallResult() End Sub Private Sub ProcessAsyncCallResult() _IsDirty = _Item.Content._IsDirty End Sub 'CustomerDetailUI code Public Sub CheckForIsDirty(ByVal myAutoResetEvent As AutoResetEvent) _AutoResetEvent = myAutoResetEvent _BfrServ.Customer_IsDirtyAsync(_Customer) 'This method initiates asynchroneous call to the web service - all the details are not shown here _AutoResetEvent.WaitOne() End Sub Private Sub _BfrServ_Customer_IsDirtyCompleted(ByVal sender As Object, ByVal e As BFRService.Customer_IsDirtyCompletedEventArgs) Handles _BfrServ.Customer_IsDirtyCompleted If _IsDirtyFromRefesh Then _IsDirtyFromRefesh = False If e.Result = True Then Me.Confirm("This customer has been modified. Are you sure you want to refresh your data ? " & vbNewLine & " Your changes will be lost.", "Yes", "No", Message.CheckIsDirtyRefresh) End If Busy.IsBusy = False Else If e.Result = True Then _IsDirty = True Me.Confirm("This customer has been modified. Would you like to save?", "Yes", "No", Message.CheckIsDirty) Else Me.Tab.Items.Remove(Me.Tab.SelectedItem) Busy.IsBusy = False End If End If _IsDirtyCompleted = True _AutoResetEvent.Set() End Sub

    Read the article

  • Avoiding .NET versioning hell

    - by moogs
    So sometimes (oftentimes!) you want to target a specific .NET version (say 3.0), but then due to some .NET service packs you get into problems like: Dispatcher.BeginInvoke(Delegate, Object[]) <-- this was added in 3.0 SP2 (3.0.30618 ) System.Threading.WaitHandle.WaitOne(Int32) <-- this was added in 3.5 SP1, 3.0 SP2, 2.0 SP2 Now, these are detected by the JIT compiler, so building against .NET 3.0 in Visual Studio won't guarante it will run on .NET 3.0 only systems. Short of confirming each and every function you use, or limiting your development environment to .NET 3.0 (which sucks since you have to develop for other projects too) what's the best way to avoid against using extensions? Thanks!

    Read the article

  • What sense does asynchronous IO make if the thread is blocked anyway (see example)

    - by codymanix
    Hello, I found an example for async ftp upload on msdn which does the following (snippet): // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback (EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); The thing what I do not understand here is, which sense does asynchronous IO make if the thread is blocked anyway with an explicit waithandle. I always thought the advantage of asynchronous IO was that the user/programm does not have to wait.

    Read the article

1 2  | Next Page >