/// <summary> /// Create an <see cref="AutoResetEvent"/> wrapper around the given native event. /// </summary> /// <param name="handle">The handle of the native event.</param> /// <returns>An <see cref="AutoResetEvent"/> wrapping the given <paramref name="handle"/>.</returns> public static AutoResetEvent GetAutoResetEvent( IntPtr handle ) { AutoResetEvent ev = new AutoResetEvent( false ); ev.Close(); GC.ReRegisterForFinalize( ev ); ev.SafeWaitHandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle( handle, false ); return ev; }
public static void Stop() { bRun = false; for (int i = 0; i < ThreadHandle.Length; i++) { AEvent.Set(); Thread.Sleep(10); } for (int i = 0; i < ThreadHandle.Length; i++) { try { if (ThreadHandle[i].ThreadState != ThreadState.Stopped) { ThreadHandle[i].Abort(); } } catch { } } if (AEvent != null) { AEvent.Close(); } }
public BackgroundDispatcher(string name) { AutoResetEvent are = new AutoResetEvent(false); Thread thread = new Thread((ThreadStart)delegate { _dispatcher = Dispatcher.CurrentDispatcher; _dispatcher.UnhandledException += delegate( object sender, DispatcherUnhandledExceptionEventArgs e) { e.Handled = true; }; are.Set(); Dispatcher.Run(); }); thread.Name = string.Format("BackgroundStaDispatcher({0})", name); thread.SetApartmentState(ApartmentState.MTA); thread.IsBackground = true; thread.Start(); are.WaitOne(); are.Close(); are.Dispose(); }
public void Download(Uri url, string saveLoc) { try { using (ExtendedWebClient setupDownloader = new ExtendedWebClient()) { setupDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(setupDownloader_DownloadProgressChanged); setupDownloader.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(setupDownloader_DownloadFileCompleted); setupDownloader.DownloadFileAsync(url, saveLoc); Console.WriteLine("Downloading setup - "); threadBlocker = new AutoResetEvent(false); threadBlocker.WaitOne(); } if (isSuccessful == false) { throw error; } } finally { if (threadBlocker != null) { threadBlocker.Close(); threadBlocker = null; } } }
public override IPlugin ExecutePlugin() { ConfigItem.PluginRunContext = this; if (Plugins.ContainsKey(ConfigItem.Url)) { _init[ConfigItem.Url] = false; IPlugin thePlugin = Plugins[ConfigItem.Url]; ProcessParametricPlugin(thePlugin); thePlugin.InitPlugin(ConfigItem, Context); thePlugin.ShowPlugin(ConfigItem, Context); return Plugins[ConfigItem.Url]; } else { AutoResetEvent theSignal = new AutoResetEvent(false); ThreadRun runThread = new ThreadRun(ConfigItem, Context, theSignal, Plugins, this); ThreadStart ts = new ThreadStart(runThread.Run); Thread td = new Thread(ts); td.SetApartmentState(ApartmentState.STA); td.IsBackground = true; td.Name = ConfigItem.Url; td.Start(); _init[ConfigItem.Url] = true; theSignal.WaitOne(); theSignal.Close(); return Plugins[ConfigItem.Url]; } }
public void Close() { try { try { _sock.Shutdown(SocketShutdown.Both); } catch { } _sock.Close(); _sock.Dispose(); if (wait != null) { wait.Close(); wait.Dispose(); wait = null; } AsynEvent.Dispose(); } catch (ObjectDisposedException) { } catch (NullReferenceException) { } }
public void Dispose() { stopRequested = true; stopWh = new AutoResetEvent(false); wh.Set(); stopWh.WaitOne(); stopWh.Close(); wh.Close(); worker.Join(); }
/// <summary>The Dispose method</summary> protected override void Dispose(bool disposeManagedResources) { if (disposeManagedResources) { StopProducer(); // dispose managed resources _producerDone.Close(); _haveData.Close(); _needData.Close(); } }
[Test] // bug #81529 public void SafeWaitHandle () { AutoResetEvent are1 = new AutoResetEvent (false); AutoResetEvent are2 = new AutoResetEvent (false); SafeWaitHandle swh1 = are1.SafeWaitHandle; SafeWaitHandle swh2 = are2.SafeWaitHandle; are1.SafeWaitHandle = are2.SafeWaitHandle; Assert.AreSame (are1.SafeWaitHandle, are2.SafeWaitHandle, "#1"); Assert.AreEqual (are1.Handle, are2.Handle, "#2"); Assert.IsFalse (are1.SafeWaitHandle.IsInvalid, "#3"); Assert.IsFalse (are1.SafeWaitHandle.IsClosed, "#4"); Assert.IsFalse (swh1.IsClosed, "#5"); Assert.IsFalse (swh1.IsInvalid, "#6"); swh1.Dispose (); are1.Close (); }
public void Handle_Valid () { AutoResetEvent are1 = new AutoResetEvent (false); SafeWaitHandle swh1 = are1.SafeWaitHandle; Assert.IsFalse (swh1.IsClosed, "#1"); Assert.IsFalse (swh1.IsInvalid, "#2"); IntPtr dummyHandle = (IntPtr) 2; are1.Handle = dummyHandle; Assert.AreEqual (are1.Handle, dummyHandle, "#3"); Assert.IsFalse (swh1.IsClosed, "#4"); Assert.IsFalse (swh1.IsClosed, "#5"); Assert.IsFalse (swh1.IsInvalid, "#6"); Assert.IsFalse (are1.SafeWaitHandle.IsClosed, "#7"); Assert.IsFalse (are1.SafeWaitHandle.IsInvalid, "#8"); are1.Close (); swh1.Dispose (); }
protected override void Dispose(bool disposing) { if (!disposed) { disposed = true; GameInstance.Components.Remove(this); if (ownsServices) { GameInstance.Components.Remove(services); services.Dispose(); } todo.Set(); thread.Join(); todo.Close(); thread = null; todo = null; } }
protected String DownloadSetup(String downloadLocation, String extn) { String tempLocationToSave = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + "." + extn); try { using (WebClient setupDownloader = new WebClient()) { setupDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(setupDownloader_DownloadProgressChanged); setupDownloader.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(setupDownloader_DownloadFileCompleted); setupDownloader.DownloadFileAsync(new Uri(downloadLocation), tempLocationToSave); Console.Write("Downloading setup - "); threadBlocker = new AutoResetEvent(false); threadBlocker.WaitOne(); } } finally { if (threadBlocker != null) { threadBlocker.Close(); } } return tempLocationToSave; }
protected void GetSearchTicket() { //从本地数据库查询 DataSet ds = new DataSet(); //查找航空公司名称 构造航空公司排序数组 string str = @"select top 100 percent"; str += " FY_Ticket.tid,FY_Ticket.untaxPrice,FY_Ticket.relayPort,FY_Ticket.tripType,"; str += " FY_FromCity.cityCode as fromCityCode,"; str += " FY_ToCity.cityCode as toCityCode,"; str += " FY_Tax.tax,"; str += " FY_FromCity.chName as fromCityname,FY_FromCity.fId,FY_Airline.aId,FY_ToCity.tId as toId,"; str += " FY_ToCity.chName as toCityname,FY_Airline.airlineCode as airlineCode,FY_Airline.chName as airname, FY_Airline.smallPic as smallPic from FY_Ticket "; str += " left join FY_FromCity on FY_FromCity.fId=FY_Ticket.fromCity"; str += " left join FY_ToCity on FY_ToCity.tId=FY_Ticket.toCity"; str += " left join FY_Airline on FY_Airline.aId=FY_Ticket.airLine"; str += " left join FY_Tax on (FY_Ticket.tripType =FY_Tax.taxType and FY_Ticket.airLine = FY_Tax.airline and FY_Ticket.toCity = FY_Tax.toCity and FY_Ticket.fromCity = FY_Tax.fromCity)"; str += " where 1=1 "; //查找航空公司 string strAirline = @"select FY_Ticket.airLine,min(FY_Ticket.untaxPrice) as untaxPrice "; strAirline += " from FY_Ticket"; strAirline += " left join FY_FromCity on FY_FromCity.fId=FY_Ticket.fromCity"; strAirline += " left join FY_ToCity on FY_ToCity.tId=FY_Ticket.toCity"; strAirline += " left join FY_Tax on (FY_Ticket.airLine = FY_Tax.airline and FY_Ticket.toCity = FY_Tax.toCity and FY_Ticket.fromCity = FY_Tax.fromCity)"; strAirline += " where 1=1 "; if (tripTypeInt != 2) { str += " and (FY_Ticket.tripType=" + tripTypeInt + ")"; strAirline += " and (FY_Ticket.tripType=" + tripTypeInt + ")"; } if (fromCityId != 0) { str += " and (FY_FromCity.fId=" + fromCityId + ")"; strAirline += " and (FY_FromCity.fId=" + fromCityId + ")"; } if (toCityNameStr != "") { str += " and (FY_ToCity.chName like '%" + toCityNameStr + "%')"; strAirline += " and (FY_ToCity.chName like '%" + toCityNameStr + "%')"; } if (tripDateStr != "") { str += " and (FY_Ticket.fromtripDate<='" + tripDateStr + "' and FY_Ticket.totripDate>='" + tripDateStr + "' )"; strAirline += " and (FY_Ticket.fromtripDate<='" + tripDateStr + "' and FY_Ticket.totripDate>='" + tripDateStr + "' )"; } if (tripDateStr != "" && backDateStr != "" && tripTypeInt != 0) { int day = (Convert.ToDateTime(backDateStr) - Convert.ToDateTime(tripDateStr)).Days; str += " and DateDiff(d,FY_Ticket.fromtripDate,FY_Ticket.totripDate) >= " + day; strAirline += " and DateDiff(d,FY_Ticket.fromtripDate,FY_Ticket.totripDate) >= " + day; } str += " and (FY_Ticket.tosaleDate>='" + DateTime.Now.ToString("yyyy-MM-dd") + "')"; strAirline += " and (FY_Ticket.tosaleDate>='" + DateTime.Now.ToString("yyyy-MM-dd") + "')"; if (airlineId != 0) { str += " and (FY_Airline.aId=" + airlineId + ")"; } if (getorderStr != "") { str += " order by FY_Ticket." + getorderStr + " asc ,FY_Ticket.tId desc"; } else { str += " order by FY_Ticket.untaxPrice asc ,FY_Ticket.tId desc"; } ArrayList allAirlines = new ArrayList(); strAirline += " group by FY_Ticket.airLine order by min(FY_Ticket.untaxPrice) asc"; //查询航空公司 DataSet dsStrAirLine = SqlHelper.ExecuteDataset(SqlHelper.ConnString_select, CommandType.Text, strAirline); if (dsStrAirLine != null) { foreach (DataRow drAifeiAirline in dsStrAirLine.Tables[0].Rows) { AiFeiAirline afa = new AiFeiAirline(); afa.minPrice = drAifeiAirline["untaxPrice"].ToString(); afa.airlineId = drAifeiAirline["airLine"].ToString(); string code = string.Empty; string pic = string.Empty; afa.airlineName = ReadXmlHelper.GetAirLineNameByID(Convert.ToInt64(afa.airlineId), out code, out pic); afa.airlinePic = pic; afa.airlineCode = code; //if(allAirlines.Count<11) allAirlines.Add(afa); } } //从爱飞网获得数据并排序 AiFeiService aifeiService = new AiFeiService(); //ArrayList = aifeiService.GlobalTicket(dpt, arr, toTime, reTime, cate); ///dpt 出发三字码 arr 到达三字码 /// string arr = getToCityCodeByName(toCityNameStr); string dpt = getFromCityCodeByName(fromCityName); //string cate = "ALL"; string cate = "SF"; ArrayList aifeiTickets = new ArrayList(); if (tripTypeInt == 0) { cate = "DC"; aifeiTickets = aifeiService.AiFeiTickets(dpt, arr, ajaxToTime, ajaxFromTime, cate, airlineId, ref allAirlines);//过滤航空公司 } else if (tripTypeInt == 1) { cate = "SF"; aifeiTickets = aifeiService.AiFeiTickets(dpt, arr, ajaxToTime, ajaxFromTime, cate, airlineId, ref allAirlines);//过滤航空公司 } else if (tripTypeInt == 2) { System.Threading.AutoResetEvent resetEvent = new System.Threading.AutoResetEvent(false); AiFeiService.AiFeiTicketsHandler d1 = new AiFeiService.AiFeiTicketsHandler(aifeiService.AiFeiTickets); AiFeiService.AiFeiTicketsHandler d2 = new AiFeiService.AiFeiTicketsHandler(aifeiService.AiFeiTickets); IAsyncResult iar1 = null, iar2 = null; ArrayList aifeiTickets2 = null; AsyncCallback back1 = delegate(IAsyncResult iar) { aifeiTickets = d1.EndInvoke(ref allAirlines, iar1); if (iar2 != null && iar2.IsCompleted) { resetEvent.Set(); } }; AsyncCallback back2 = delegate(IAsyncResult iar) { aifeiTickets2 = d2.EndInvoke(ref allAirlines, iar2); if (iar1 != null && iar1.IsCompleted) { resetEvent.Set(); } }; iar1 = d1.BeginInvoke(dpt, arr, ajaxToTime, ajaxFromTime, "SF", airlineId, ref allAirlines, back1, null); iar2 = d2.BeginInvoke(dpt, arr, ajaxToTime, ajaxFromTime, "DC", airlineId, ref allAirlines, back2, null); if (resetEvent.WaitOne(2000, true)) { resetEvent.Close(); } if (aifeiTickets2 != null) { for (int i = 0; i < aifeiTickets2.Count; i++) { aifeiTickets.Add(aifeiTickets2[i]); } } } //获得爱飞机票列表 ArrayList tickets = new ArrayList(); ArrayList feiYingTickets = new ArrayList(); int aifeinum = Convert.ToInt32(this.hidd_aifeinum.Value); ds = SqlHelper.ExecuteDataset(SqlHelper.ConnString_select, CommandType.Text, str); //没数据 显示提示 if ((ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0) && aifeiTickets.Count == 0) { this.panHaveValue2.Visible = false; this.panNoValue.Visible = true; return; } else { this.panHaveValue2.Visible = true; this.panNoValue.Visible = false; DataTable dt = ds.Tables[0]; //遍历行 foreach (DataRow dr in dt.Rows) { //遍历列 AiFeiTicket aifeiTicket = new AiFeiTicket(); aifeiTicket.ticketId = dr["tid"].ToString().Trim(); aifeiTicket.price = Convert.ToInt32(dr["untaxPrice"].ToString()); aifeiTicket.fromCity = dr["fromCityName"].ToString(); aifeiTicket.fromCityCode = dr["fromCityCode"].ToString(); aifeiTicket.fromCityId = dr["fId"].ToString(); aifeiTicket.toCity = dr["toCityName"].ToString(); aifeiTicket.toCityCode = dr["toCityCode"].ToString(); aifeiTicket.toCityId = dr["toId"].ToString(); aifeiTicket.airlineCode = dr["airlineCode"].ToString(); aifeiTicket.airline = dr["airname"].ToString(); aifeiTicket.airlineId = dr["aId"].ToString(); aifeiTicket.airlineSmallPic = dr["smallPic"].ToString(); aifeiTicket.relayPort = dr["relayPort"].ToString(); aifeiTicket.sourceType = "feiying"; aifeiTicket.tripType = dr["tripType"].ToString();//单程or往返 //查询税费信息 //aifeiTicket.tax = getTaxMessage(aifeiTicket.fromCityId, aifeiTicket.toCityId, aifeiTicket.airlineId, Convert.ToInt32(aifeiTicket.tripType)); feiYingTickets.Add(aifeiTicket); } } if (getorderStr.Equals("")) { //排序飞瀛机票 foreach (AiFeiTicket orderTicket in feiYingTickets) { if (tickets.Count == 0) { tickets.Add(orderTicket); } else { bool isEnd = false; for (int i = 0; i < tickets.Count && !isEnd; i++) { AiFeiTicket aft = (AiFeiTicket)tickets[i]; if ((i + 1) == tickets.Count && orderTicket.price > aft.price) { tickets.Add(orderTicket); isEnd = true; break; } else if (orderTicket.price <= aft.price) { tickets.Insert(i, orderTicket); isEnd = true; break; } } } } //排序爱飞机票 foreach (AiFeiTicket orderTicket in aifeiTickets) { if (tickets.Count == 0) { tickets.Add(orderTicket); } else { bool isEnd = false; for (int i = 0; i < tickets.Count && !isEnd; i++) { AiFeiTicket aft = (AiFeiTicket)tickets[i]; if ((i + 1) == tickets.Count && orderTicket.price > aft.price) { tickets.Add(orderTicket); isEnd = true; break; } else if (orderTicket.price < aft.price) { tickets.Insert(i, orderTicket); isEnd = true; break; } else if (orderTicket.price == aft.price && orderTicket.airlineCode.Equals(aft.airlineCode)) { isEnd = true; break; } } } } } else if (getorderStr.Equals("airLine")) { //航空公司排序 tickets = feiYingTickets; //排序爱飞机票 foreach (AiFeiTicket orderTicket in aifeiTickets) { if (tickets.Count == 0) { tickets.Add(orderTicket); } else { bool isEnd = false; for (int i = 0; i < tickets.Count && !isEnd; i++) { AiFeiTicket aft = (AiFeiTicket)tickets[i]; if ((i + 1) == tickets.Count && orderTicket.price > aft.price && orderTicket.airlineCode.Equals(aft.airlineCode)) { tickets.Add(orderTicket); isEnd = true; break; } else if (orderTicket.price < aft.price && orderTicket.airlineCode.Equals(aft.airlineCode)) { tickets.Insert(i, orderTicket); isEnd = true; break; } else if (orderTicket.price == aft.price && orderTicket.airlineCode.Equals(aft.airlineCode)) { isEnd = true; break; } } } } } //绑定航空公司 Session["TicketsSessionKey_Airlines"] = allAirlines; //写入Session 分页使用 Session["TicketsSessionKey_" + tripTypeInt + "_" + fromCityId + "_" + Server.HtmlEncode(toCityNameStr) + "_" + ajaxToTime + "_" + ajaxFromTime] = tickets; this.BindData(tickets); }
//private void ShowAvatar(Avatar av) //{ // GLAvatar ga = new GLAvatar(); // RenderAvatar ra = new Rendering.RenderAvatar(); // ra.avatar = av; // ra.glavatar = ga; // updateAVtes(ra); // ra.glavatar.morph(av); //} private void UpdatePrimBlocking(Primitive prim) { FacetedMesh mesh = null; FacetedMesh existingMesh = null; lock (Prims) { if (Prims.ContainsKey(prim.LocalID)) { existingMesh = Prims[prim.LocalID]; } } if (prim.Textures == null) return; //if (prim.PrimData.PCode == PCode.Avatar) //{ // ShowAvatar(client.Network.CurrentSim.ObjectsAvatars[prim.LocalID]); //} try { if (prim.Sculpt != null && prim.Sculpt.SculptTexture != UUID.Zero) { if (prim.Sculpt.Type != SculptType.Mesh) { // Regular sculptie Image img = null; if (!LoadTexture(prim.Sculpt.SculptTexture, ref img, true)) return; mesh = renderer.GenerateFacetedSculptMesh(prim, (Bitmap)img, DetailLevel.Highest); } else { // Mesh AutoResetEvent gotMesh = new AutoResetEvent(false); bool meshSuccess = false; client.Assets.RequestMesh(prim.Sculpt.SculptTexture, (success, meshAsset) => { if (!success || !meshAsset.Decode()) { Logger.Log("Failed to fetch or decode the mesh asset", Helpers.LogLevel.Warning, client); } else { mesh = GenerateFacetedMesh(prim, meshAsset.MeshData, DetailLevel.Highest); meshSuccess = true; } gotMesh.Set(); }); if (!gotMesh.WaitOne(20 * 1000, false)) { gotMesh.Close(); return; } if (!meshSuccess) { gotMesh.Close(); return; } } } else { mesh = renderer.GenerateFacetedMesh(prim, DetailLevel.Highest); } } catch { return; } // Create a FaceData struct for each face that stores the 3D data // in a OpenGL friendly format for (int j = 0; j < mesh.Faces.Count; j++) { Face face = mesh.Faces[j]; FaceData data = new FaceData(); // Vertices for this face data.Vertices = new float[face.Vertices.Count * 3]; data.Normals = new float[face.Vertices.Count * 3]; for (int k = 0; k < face.Vertices.Count; k++) { data.Vertices[k * 3 + 0] = face.Vertices[k].Position.X; data.Vertices[k * 3 + 1] = face.Vertices[k].Position.Y; data.Vertices[k * 3 + 2] = face.Vertices[k].Position.Z; data.Normals[k * 3 + 0] = face.Vertices[k].Normal.X; data.Normals[k * 3 + 1] = face.Vertices[k].Normal.Y; data.Normals[k * 3 + 2] = face.Vertices[k].Normal.Z; } // Indices for this face data.Indices = face.Indices.ToArray(); // Texture transform for this face Primitive.TextureEntryFace teFace = prim.Textures.GetFace((uint)j); if (teFace != null) renderer.TransformTexCoords(face.Vertices, face.Center, teFace, mesh.Prim.Scale); // Texcoords for this face data.TexCoords = new float[face.Vertices.Count * 2]; for (int k = 0; k < face.Vertices.Count; k++) { data.TexCoords[k * 2 + 0] = face.Vertices[k].TexCoord.X; data.TexCoords[k * 2 + 1] = face.Vertices[k].TexCoord.Y; } // Set the UserData for this face to our FaceData struct face.UserData = data; mesh.Faces[j] = face; if (existingMesh != null && j < existingMesh.Faces.Count && existingMesh.Faces[j].TextureFace.TextureID == teFace.TextureID && ((FaceData)existingMesh.Faces[j].UserData).TexturePointer != 0 ) { FaceData existingData = (FaceData)existingMesh.Faces[j].UserData; data.TexturePointer = existingData.TexturePointer; } else { var textureItem = new TextureLoadItem() { Data = data, Prim = prim, TeFace = teFace }; PendingTextures.Enqueue(textureItem); } } lock (Prims) { Prims[prim.LocalID] = mesh; } mesh = null; existingMesh = null; GLInvalidate(); }
private void WaitForDeploymentComplete(string requestToken) { AutoResetEvent threadBlocker = null; try { threadBlocker = new AutoResetEvent(false); deployAppWaitTimer = new System.Timers.Timer(5000); deployAppWaitTimer.Elapsed += new ElapsedEventHandler( delegate(object sender, ElapsedEventArgs e) { string requestUri; string responseXml; bool isError; HttpWebRequest webRequest; HttpWebResponse webResponse = null; try { Console.Write("Storage account creation status: "); deployAppWaitTimer.Stop(); requestUri = string.Format("https://management.core.windows.net/{0}/operations/{1}", _subscriptionId, requestToken); webRequest = (HttpWebRequest)WebRequest.Create(requestUri); webRequest.Method = "GET"; webRequest.ClientCertificates.Add(_cert); webRequest.Headers.Add("x-ms-version", "2009-10-01"); webResponse = (HttpWebResponse)webRequest.GetResponse(); if (webResponse.StatusCode != HttpStatusCode.OK) { throw new Exception(@"Error fetching status code for creating storage account. Error code - " + webResponse.StatusCode.ToString() + " Description - " + webResponse.StatusDescription); } using (Stream responseStream = webResponse.GetResponseStream()) using (StreamReader responseStreamReader = new StreamReader(responseStream)) { responseXml = responseStreamReader.ReadToEnd(); if (IsDeploymentComplete(responseXml, out isError) == true) { Console.WriteLine("Successfull."); deployAppWaitTimer.Dispose(); threadBlocker.Set(); } else if (isError == true) //Give up. { Console.WriteLine("Failed."); deployAppWaitTimer.Dispose(); threadBlocker.Set(); } else { Console.WriteLine("In progress."); deployAppWaitTimer.Start(); } } } finally { if (webResponse != null) webResponse.Close(); } }); deployAppWaitTimer.Start(); threadBlocker.WaitOne(); } finally { if (threadBlocker != null) threadBlocker.Close(); } }
protected void GetSearchTicket() { DataSet airlines = this.getAirLineDataSets();//获取航空公司 System.Threading.AutoResetEvent resetEvent = new System.Threading.AutoResetEvent(false); getFei580TicektHandler d1 = new getFei580TicektHandler(getFei580Ticekt); getKABETiceketHandler d2 = new getKABETiceketHandler(getKABETiceket); IAsyncResult iar1 = null, iar2 = null; ArrayList tickets1 = null, tickets2 = null; AsyncCallback back1 = delegate(IAsyncResult iar) { try { tickets1 = d1.EndInvoke(iar1); if (iar2 != null && iar2.IsCompleted) { resetEvent.Set(); } } catch { resetEvent.Set(); } }; AsyncCallback back2 = delegate(IAsyncResult iar) { try { tickets2 = d2.EndInvoke(iar2); if (iar1 != null && iar1.IsCompleted) { resetEvent.Set(); } } catch { resetEvent.Set(); } }; iar1 = d1.BeginInvoke(back1, null); iar2 = d2.BeginInvoke(getAirLineCode(airlines, this.airlineId), back2, null); if (resetEvent.WaitOne(8000, true)) { resetEvent.Close(); } //没数据 显示提示 if ((tickets1 == null || tickets1.Count == 0) && (tickets2 == null || tickets2.Count == 0)) { this.panHaveValue2.Visible = false; this.panNoValue.Visible = true; return; } else { this.panHaveValue2.Visible = true; this.panNoValue.Visible = false; } ArrayList tickets = new ArrayList(); if (string.IsNullOrEmpty(this.orderStr)) { //排序飞瀛机票 foreach (kabe_flight ordertickets in tickets1) { if (tickets.Count == 0) { tickets.Add(ordertickets); } else { bool isEnd = false; for (int i = 0; i < tickets.Count && !isEnd; i++) { kabe_flight aft = (kabe_flight)tickets[i]; if ((i + 1) == tickets.Count && ordertickets.adultprice > aft.adultprice) { tickets.Add(ordertickets); isEnd = true; break; } else if (ordertickets.adultprice <= aft.adultprice) { tickets.Insert(i, ordertickets); isEnd = true; break; } } } } //排序Kabe机票 if (tickets2 != null) { foreach (kabe_flight ordertickets in tickets2) { if (tickets.Count == 0) { tickets.Add(ordertickets); } else { bool isEnd = false; for (int i = 0; i < tickets.Count && !isEnd; i++) { kabe_flight aft = (kabe_flight)tickets[i]; if ((i + 1) == tickets.Count && ordertickets.adultprice > aft.adultprice) { tickets.Add(ordertickets); isEnd = true; break; } else if (ordertickets.adultprice < aft.adultprice) { tickets.Insert(i, ordertickets); isEnd = true; break; } else if (ordertickets.adultprice == aft.adultprice && ordertickets.airline.Equals(aft.airline)) { isEnd = true; break; } } } } } } else if (this.orderStr.Trim() == "airLine") { //航空公司排序 tickets = tickets1; //排序kabe机票 foreach (kabe_flight ordertickets in tickets2) { if (tickets.Count == 0) { tickets.Add(ordertickets); } else { bool isEnd = false; for (int i = 0; i < tickets.Count && !isEnd; i++) { kabe_flight aft = (kabe_flight)tickets[i]; if ((i + 1) == tickets.Count && ordertickets.adultprice > aft.adultprice && ordertickets.airline.Equals(aft.airline)) { tickets.Add(ordertickets); isEnd = true; break; } else if (ordertickets.adultprice < aft.adultprice && ordertickets.airline.Equals(aft.airline)) { tickets.Insert(i, ordertickets); isEnd = true; break; } else if (ordertickets.adultprice == aft.adultprice && ordertickets.airline.Equals(aft.airline)) { tickets.Insert(i, ordertickets); isEnd = true; break; } } if (!isEnd) { tickets.Add(ordertickets); } } } } // if (Session["TicketsSessionKey_Airlines"] == null) { ArrayList airlinesresult = new ArrayList(); foreach (DataRow dr in airlines.Tables[0].Rows) { foreach (kabe_flight ordertickets in tickets) { if (dr["airlinecode"].ToString().Trim().ToLower() == ordertickets.airline.Trim().ToLower()) { kabe_Airline a = new kabe_Airline(); a.airlineId = dr["aId"].ToString(); a.airlineCode = dr["airlinecode"].ToString(); a.airlineName = dr["chName"].ToString(); a.airlinePic = dr["smallPic"].ToString(); airlinesresult.Add(a); break; } } } //写入Session 分页使用 Session["TicketsSessionKey_Airlines"] = airlinesresult; } Session["TicketsSessionKey_KaBaTickets"] = tickets2; Session[string.Format("TicketsSessionKey_{0}_{1}_{2}_{3}_{4}", this.tripType, fromcityCode, this.tocityCode, Convert.ToDateTime(this.tripDate).ToString("yyyyMMdd"), Convert.ToDateTime(this.backDate).ToString("yyyyMMdd"))] = tickets; this.BindData(tickets); }
public void StartScheduler(IMFClock pClock) { if (m_bSchedulerThread != false) { throw new COMException("Scheduler already started", E_Unexpected); } m_pClock = pClock; // Set a high the timer resolution (ie, short timer period). timeBeginPeriod(1); // Create an event to wait for the thread to start. m_hThreadReadyEvent = new AutoResetEvent(false); try { // Use the c# threadpool to avoid creating a thread // when streaming begins ThreadPool.QueueUserWorkItem(new WaitCallback(SchedulerThreadProcPrivate)); m_hThreadReadyEvent.WaitOne(SCHEDULER_TIMEOUT, false); m_bSchedulerThread = true; } finally { // Regardless success/failure, we are done using the "thread ready" event. m_hThreadReadyEvent.Close(); m_hThreadReadyEvent = null; } }
/// <summary> /// Reads the specified read list. /// </summary> /// <param name="readList">The read list. The first tuple item specifies /// where in the result array to put the read result.</param> /// <param name="readResults">The read results.</param> /// <param name="tm">The tm.</param> /// <returns>The list of indices of failed items in the readlist.</returns> private List<int> Read(List<Tuple<int, long, int>> readList, byte[][] readResults, TorrentManager tm) { var failedItems = new List<int>(); for (int i = 0; i < readList.Count(); i++) { var tuple = readList[i]; AutoResetEvent waitHandle = new AutoResetEvent(false); int resultIndex = tuple.Item1; long offset = tuple.Item2; int count = tuple.Item3; byte[] buffer = new byte[count]; bool successful = false; _diskManager.QueueRead(tm, offset, buffer, count, delegate(bool succ) { // DiskManager with DedupDiskWriter reads data according to // mappings for deduplicated data. successful = succ; if (succ) { logger.DebugFormat("Read (offset, count) = ({0}, {1}) successful.", offset, count); readResults[resultIndex] = buffer; } else { failedItems.Add(i); } waitHandle.Set(); }); waitHandle.WaitOne(); waitHandle.Close(); } return failedItems; }
private void Ping() { if (this.Device != null && this.Device.ID != 0) { try { AutoResetEvent waiter = new AutoResetEvent(false); Ping pingSender = new Ping(); pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback); IPAddress address = IPAddress.Parse(this.Device.IP); ; int timeout = 3000; pingSender.SendAsync(address, timeout, waiter); waiter.Close(); } catch (Exception) { } } }
void CloseWait() { AutoResetEvent waitHandle = this.waitHandle; this.waitHandle = null; if (waitHandle != null) { waitHandle.Set(); waitHandle.Close(); } }
public void StartWatcher() { m_bRun = true; var wh = new AutoResetEvent(false); var fsw = new FileSystemWatcher("."); fsw.Filter = m_logfileName; fsw.Changed += (s, e) => wh.Set(); try { var fs = new FileStream(m_logfileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); fs.Seek(0, SeekOrigin.End); using (var sr = new StreamReader(fs)) { var s = ""; while (m_bRun == true) { s = sr.ReadLine(); if (s != null) { foreach (string search in searchLinesInclude) { if (s.Contains(search) && !searchLinesExclude.Any(s.Contains)) { if (SendEmail(search, s)) { m_processed++; SetProcessed(Color.Blue, Color.White); SetTitle(System.IO.Path.GetFileName(m_logfileName)); m_timer.Enabled = true; } break; } } } else { wh.WaitOne(1000); } } } } catch (Exception e) { Debug.WriteLine(e.Message); SetStatus("Error processing file"); } wh.Close(); m_finishedEvent.Set(); }
private string GetObjectName(Primitive prim, int distance) { string name = "Loading..."; string ownerName = "Loading..."; if (prim.Properties == null) { //if (prim.ParentID != 0) throw new Exception("Requested properties for non root prim"); propRequester.RequestProps(prim.LocalID); } else { name = prim.Properties.Name; // prim.Properties.GroupID is the actual group when group owned, not prim.GroupID if (UUID.Zero == prim.Properties.OwnerID && PrimFlags.ObjectGroupOwned == (prim.Flags & PrimFlags.ObjectGroupOwned) && UUID.Zero != prim.Properties.GroupID) { System.Threading.AutoResetEvent nameReceivedSignal = new System.Threading.AutoResetEvent(false); EventHandler<GroupNamesEventArgs> cbGroupName = new EventHandler<GroupNamesEventArgs>( delegate(object sender, GroupNamesEventArgs e) { if (e.GroupNames.ContainsKey(prim.Properties.GroupID)) { e.GroupNames.TryGetValue(prim.Properties.GroupID, out ownerName); if (string.IsNullOrEmpty(ownerName)) ownerName = "Loading..."; if (null != nameReceivedSignal) nameReceivedSignal.Set(); } }); client.Groups.GroupNamesReply += cbGroupName; client.Groups.RequestGroupName(prim.Properties.GroupID); nameReceivedSignal.WaitOne(5000, false); nameReceivedSignal.Close(); client.Groups.GroupNamesReply -= cbGroupName; } else ownerName = instance.Names.Get(prim.Properties.OwnerID); } return String.Format("{0} ({1}m) owned by {2}", name, distance, ownerName); }
private void RunPolling() { IsPolling = true; while (true) { try { waitHandle = new AutoResetEvent(false); while (!stopRequested) { OnPollingStarted(); FetchJobResults(); OnPollingFinished(); waitHandle.WaitOne(Interval); } waitHandle.Close(); IsPolling = false; return; } catch (Exception e) { OnExceptionOccured(e); if (!autoResumeOnException) { waitHandle.Close(); IsPolling = false; return; } } } }
[Test] // bug #81529 public void Handle_Invalid () { AutoResetEvent are1 = new AutoResetEvent (false); SafeWaitHandle swh1 = are1.SafeWaitHandle; are1.Handle = (IntPtr) (-1); Assert.IsTrue (swh1 != are1.SafeWaitHandle, "#1"); Assert.IsFalse (swh1.IsClosed, "#2"); Assert.IsFalse (swh1.IsInvalid, "#3"); Assert.IsFalse (are1.SafeWaitHandle.IsClosed, "#4"); Assert.IsTrue (are1.SafeWaitHandle.IsInvalid, "#5"); are1.Close (); swh1.Dispose (); }
public void Dispose() { if (SetDisposed ()) { AutoResetEvent disposeHandle = new AutoResetEvent (false); feed_manager.Dispose (disposeHandle); enclosure_manager.Dispose (disposeHandle); if (command_queue != null) { command_queue.Dispose (); command_queue = null; } disposeHandle.Close (); } }
private String DownloadCouchDbSetup() { try { String tempLocationToSave = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); using (WebClient setupDownloader = new WebClient()) { setupDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(setupDownloader_DownloadProgressChanged); setupDownloader.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(setupDownloader_DownloadFileCompleted); setupDownloader.DownloadFileAsync(new Uri(CouchDBSetupPath), tempLocationToSave); Console.Write("Downloading CouchDB setup - "); threadBlocker = new AutoResetEvent(false); threadBlocker.WaitOne(); if (downloadException != null) { throw downloadException; } } return tempLocationToSave; } finally { if (threadBlocker != null) { threadBlocker.Close(); } } }
/// <summary>发送并接收消息。主要用于应答式的请求和响应。</summary> /// <remarks>如果内部实现是异步模型,则等待指定时间获取异步返回的第一条消息,该消息不再触发消息到达事件<see cref="OnReceived"/>。</remarks> /// <param name="message"></param> /// <param name="millisecondsTimeout">等待的毫秒数,或为 <see cref="F:System.Threading.Timeout.Infinite" /> (-1),表示无限期等待。默认0表示不等待</param> /// <returns></returns> public virtual Message SendAndReceive(Message message, Int32 millisecondsTimeout = 0) { Send(message); var _wait = new AutoResetEvent(true); _wait.Reset(); Message msg = null; innerOnReceived += (s, e) => { msg = e.Message; _wait.Set(); }; //if (!_wait.WaitOne(millisecondsTimeout, true)) return null; _wait.WaitOne(millisecondsTimeout, false); _wait.Close(); return msg; }
/// <summary> /// 根据查询的城市获取爱飞信息并记录到数据库并返回单程和双程的参数数据 /// </summary> /// <param name="result1"></param> /// <param name="result2"></param> protected void getKABERealTimeTiceket(out System.Xml.XmlNode result1, out System.Xml.XmlNode result2) { result1 = null; result2 = null; KABE.Service service = new KABE.Service(); if (this.tripType == 0) { result1 = this.GetKabe_InterDetailFlt(this.fromcityCode, this.tocityCode, this.tripDate, "", "", "Y", "1"); if (result1 != null) { return; } result1 = service.getInterDetailFltValuesV3(this.fromcityCode, this.tocityCode, this.tripDate, "", "", "Y", "1", "437c1d948857da89467d2428c408f3d9"); if (result1.SelectSingleNode("code").InnerText == "0")//成功记录到数据库 { kabe_InterDetailFltEntity model = new kabe_InterDetailFltEntity(); model.sc = this.fromcityCode; model.ec = this.tocityCode; model.sd = this.tripDate; model.ed = string.Empty; model.classtype = "Y"; model.ft = "1"; model.result = result1; this.InsertKabe_InterDetailFlt(model); } } else if (this.tripType == 1) { result1 = this.GetKabe_InterDetailFlt(this.fromcityCode, this.tocityCode, this.tripDate, this.backDate, "", "Y", "2"); if (result1 != null) { return; } result1 = service.getInterDetailFltValuesV3(this.fromcityCode, this.tocityCode, this.tripDate, this.backDate, "", "Y", "2", "437c1d948857da89467d2428c408f3d9"); if (result1.SelectSingleNode("code").InnerText == "0")//成功记录到数据库 { kabe_InterDetailFltEntity model = new kabe_InterDetailFltEntity(); model.sc = this.fromcityCode; model.ec = this.tocityCode; model.sd = this.tripDate; model.ed = this.backDate; model.classtype = "Y"; model.ft = "2"; model.result = result1; this.InsertKabe_InterDetailFlt(model); } } else if (this.tripType == 2) { result1 = this.GetKabe_InterDetailFlt(this.fromcityCode, this.tocityCode, this.tripDate, "", "", "Y", "1"); result2 = this.GetKabe_InterDetailFlt(this.fromcityCode, this.tocityCode, this.tripDate, this.backDate, "", "Y", "2"); System.Xml.XmlNode res1 = result1, res2 = result2; System.Threading.AutoResetEvent resetEvent = new System.Threading.AutoResetEvent(false); System.Xml.XmlNode result3 = null, result4 = null; IAsyncResult iar1 = null, iar2 = null; AsyncCallback back1 = delegate(IAsyncResult iar) { try { result3 = service.EndgetInterDetailFltValuesV3(iar1); if (result3.SelectSingleNode("code").InnerText == "0")//成功记录到数据库 { kabe_InterDetailFltEntity model = new kabe_InterDetailFltEntity(); model.sc = this.fromcityCode; model.ec = this.tocityCode; model.sd = this.tripDate; model.ed = string.Empty; model.classtype = "Y"; model.ft = "1"; model.result = result3; this.InsertKabe_InterDetailFlt(model); } if ((iar2 != null && iar2.IsCompleted) || res2 != null) { resetEvent.Set(); } } catch { resetEvent.Set(); } }; AsyncCallback back2 = delegate(IAsyncResult iar) { try { result4 = service.EndgetInterDetailFltValuesV3(iar2); if (result4.SelectSingleNode("code").InnerText == "0")//成功记录到数据库 { kabe_InterDetailFltEntity model = new kabe_InterDetailFltEntity(); model.sc = this.fromcityCode; model.ec = this.tocityCode; model.sd = this.tripDate; model.ed = this.backDate; model.classtype = "Y"; model.ft = "2"; model.result = result4; this.InsertKabe_InterDetailFlt(model); } if ((iar1 != null && iar1.IsCompleted) || res1 != null) { resetEvent.Set(); } } catch { resetEvent.Set(); } }; if (result1 == null) { iar1 = service.BegingetInterDetailFltValuesV3(this.fromcityCode, this.tocityCode, this.tripDate, "", "", "Y", "1", "437c1d948857da89467d2428c408f3d9", back1, null); } if (result2 == null) { iar2 = service.BegingetInterDetailFltValuesV3(this.fromcityCode, this.tocityCode, this.tripDate, this.backDate, "", "Y", "2", "437c1d948857da89467d2428c408f3d9", back2, null); } if (result1 == null || result2 == null) { if (resetEvent.WaitOne(5000, true)) { resetEvent.Close(); } } if (result1 == null) { result1 = result3; } if (result2 == null) { result2 = result4; } } }
private void CreateBlockEvent() { AutoResetEvent are = new AutoResetEvent(false); if (Interlocked.CompareExchange<AutoResetEvent>(ref blockEvent, are, null) != null) { are.Close(); } }
private string Download() { try { String tempLocationToSave = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".msi"); using (WebClient setupDownloader = new WebClient()) { setupDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(setupDownloader_DownloadProgressChanged); setupDownloader.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(setupDownloader_DownloadFileCompleted); setupDownloader.DownloadFileAsync(new Uri(DownloadLoc), tempLocationToSave); Console.Write("Downloading OSS Deployment Cmdlets setup - "); threadBlocker = new AutoResetEvent(false); threadBlocker.WaitOne(); } return tempLocationToSave; } finally { if (threadBlocker != null) { threadBlocker.Close(); } } }
protected override void Run() { Logger.Write(_threadName + " thread started."); _wakeUpEvent = new AutoResetEvent(false); try { Logger.Write("Starting service."); _messenger.ConnectionEstablished += NameserverProcessor_ConnectionEstablished; _messenger.ConnectingException += NameserverProcessor_ConnectingException; _messenger.Nameserver.ExceptionOccurred += Nameserver_ExceptionOccurred; _messenger.Nameserver.AuthenticationError += Nameserver_AuthenticationError; _messenger.Nameserver.ServerErrorReceived += Nameserver_ServerErrorReceived; _messenger.Nameserver.SignedIn += Nameserver_SignedIn; _messenger.MessageManager.TextMessageReceived += MessageManager_TextMessageReceived; _messenger.Nameserver.ContactOnline += Nameserver_ContactOnline; _messenger.Nameserver.ContactOffline += Nameserver_ContactOffline; _nextPersonalMessageRefreshTime = DateTime.Now.AddSeconds(5); _nextAlertsCheckTime = DateTime.Now.AddSeconds(_checkAlertsIntervalSeconds); do { try { EnsureArgusTVConnection(); if (Proxies.IsInitialized) { EnsureEventListenerTaskStarted(); if (_messenger.Connected) { if (_messenger.Nameserver.IsSignedIn) { if (_refreshMessageAndStatus) { RefreshBotPersonalMessage(); _refreshMessageAndStatus = false; } // If needed, make sure our contact list is up-to-date. if (!_contactsValidated) { ValidateContacts(); _contactsValidated = true; } if (DateTime.Now >= _nextPersonalMessageRefreshTime) { _nextPersonalMessageRefreshTime = DateTime.MaxValue; RefreshBotPersonalMessage(); } if (_messenger.Owner.Name != "ARGUS TV") { _messenger.Owner.Name = "ARGUS TV"; } if (DateTime.Now >= _nextAlertsCheckTime) { HandleAlerts(); _nextAlertsCheckTime = DateTime.Now.AddSeconds(_checkAlertsIntervalSeconds); } } else { //Logger.Verbose("Connected to Windows Live, but not signed in yet..."); } } else { _messenger.Credentials.Account = Proxies.ConfigurationService.GetStringValue(ConfigurationModule.Messenger, ConfigurationKey.Messenger.MsnAccount).Result; _messenger.Credentials.Password = Proxies.ConfigurationService.GetStringValue(ConfigurationModule.Messenger, ConfigurationKey.Messenger.MsnPassword).Result; if (!String.IsNullOrEmpty(_messenger.Credentials.Account)) { Logger.Info("Connecting to Windows Live as '{0}'...", _messenger.Credentials.Account); _messenger.Connect(); } } } } catch (Exception ex) { Logger.Error(ex.ToString()); if (_messenger.Connected) { DisconnectMessenger(); } } } while (0 != WaitHandle.WaitAny(new WaitHandle[] { this.StopThreadEvent, _wakeUpEvent }, 1000, false)); if (_messenger.Connected) { DisconnectMessenger(); } Logger.Write("Service ended."); } catch (Exception ex) { Logger.Error(ex.ToString()); using (ServiceController controller = new ServiceController("ArgusTVMessenger")) { try { controller.Stop(); } catch { } } } finally { _wakeUpEvent.Close(); _wakeUpEvent = null; StopEventListenerTask(); } Logger.Write(_threadName + " thread ended."); }
private String DownloadWebPICmdLine() { try { String tempLocationToSave = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".zip"); using (WebClient setupDownloader = new WebClient()) { setupDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(setupDownloader_DownloadProgressChanged); setupDownloader.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(setupDownloader_DownloadFileCompleted); setupDownloader.DownloadFileAsync(new Uri(Resources.WebPICmdlineURL), tempLocationToSave); Console.Write("Downloading AzureSDKForNode.JS setup - "); threadBlocker = new AutoResetEvent(false); threadBlocker.WaitOne(); } return tempLocationToSave; } finally { if (threadBlocker != null) { threadBlocker.Close(); } } }
internal Dispatcher StartUpAndReturnDispatcher() { _startupCompleted = new AutoResetEvent(false); Thread inkingThread = new Thread(new ThreadStart(InkingThreadProc)); inkingThread.SetApartmentState(ApartmentState.STA); inkingThread.IsBackground = true; // Don't keep process alive if this thread still running. inkingThread.Start(); _startupCompleted.WaitOne(); _startupCompleted.Close(); _startupCompleted = null; return _dispatcher; }
private static DebugAttach InjectDebugger(string dllPath, IntPtr hProcess, IntPtr hKernel32, int portNum, int pid, Guid debugId, string debugOptions, EventWaitHandle attachDoneEvent) { // create our our shared memory region so that we can read the port number from the other side and we can indicate when // the attach has completed try { using (MemoryMappedFile sharedMemoryComm = MemoryMappedFile.CreateNew("PythonDebuggerMemory" + pid, 1000, MemoryMappedFileAccess.ReadWrite)) { using (var viewStream = sharedMemoryComm.CreateViewStream()) { // write the information the process needs to communicate with us. This includes: // the port number it should connect to for communicating with us // debug options flags // two auto reset events. // The first signals with the attach is ready to start (the port is open) // The second signals when the attach is completely finished // space for reporting back an error and the version of the Python interpreter attached to. viewStream.Write(BitConverter.GetBytes(portNum), 0, 4); viewStream.Write(new byte[4], 0, 4); // padding // write a handle for shared process communication AutoResetEvent attachStarting = new AutoResetEvent(false); EventWaitHandle attachDone = attachDoneEvent ?? new AutoResetEvent(false); try { #pragma warning disable 618 IntPtr attachStartingSourceHandle = attachStarting.Handle, attachDoneSourceHandle = attachDone.Handle; #pragma warning restore 618 IntPtr attachStartingTargetHandle, attachDoneTargetHandle; bool res = NativeMethods.DuplicateHandle(NativeMethods.GetCurrentProcess(), attachStartingSourceHandle, hProcess, out attachStartingTargetHandle, 0, false, (uint)DuplicateOptions.DUPLICATE_SAME_ACCESS); if (!res) { throw new Win32Exception(Marshal.GetLastWin32Error()); } res = NativeMethods.DuplicateHandle(NativeMethods.GetCurrentProcess(), attachDoneSourceHandle, hProcess, out attachDoneTargetHandle, 0, false, (uint)DuplicateOptions.DUPLICATE_SAME_ACCESS); if (!res) { throw new Win32Exception(Marshal.GetLastWin32Error()); } viewStream.Write(BitConverter.GetBytes(attachStartingTargetHandle.ToInt64()), 0, 8); viewStream.Write(BitConverter.GetBytes(attachDoneTargetHandle.ToInt64()), 0, 8); var errorCodePosition = viewStream.Position; viewStream.Write(new byte[8], 0, 8); // write null bytes for error code and version byte[] szDebugId = Encoding.ASCII.GetBytes(debugId.ToString().PadRight(64, '\0')); viewStream.Write(szDebugId, 0, szDebugId.Length); byte[] szDebugOptions = Encoding.ASCII.GetBytes(debugOptions + '\0'); viewStream.Write(szDebugOptions, 0, szDebugOptions.Length); var injectDllError = InjectDll(dllPath, hProcess, hKernel32); if (injectDllError != ConnErrorMessages.None) { return new DebugAttach(injectDllError); } viewStream.Position = errorCodePosition; byte[] buffer = new byte[4]; if (!attachStarting.WaitOne(10000)) { viewStream.Read(buffer, 0, 4); var errorMsg = (ConnErrorMessages)BitConverter.ToInt32(buffer, 0); return new DebugAttach(errorMsg != ConnErrorMessages.None ? errorMsg : ConnErrorMessages.TimeOut); } viewStream.Read(buffer, 0, 4); byte[] versionBuffer = new byte[4]; viewStream.Read(versionBuffer, 0, 4); int version = BitConverter.ToInt32(versionBuffer, 0); return new DebugAttach(attachDone, (ConnErrorMessages)BitConverter.ToInt32(buffer, 0), version); } finally { attachStarting.Close(); } } } } catch (IOException) { return new DebugAttach(ConnErrorMessages.CannotOpenProcess); } }
internal static void CleanEventVars(ref RegisteredWaitHandle waitHandle, ref SafeCollabEvent safeEvent, ref AutoResetEvent firedEvent) { if (waitHandle != null){ waitHandle.Unregister(null); waitHandle = null; } if ((safeEvent != null) && (!safeEvent.IsInvalid)){ safeEvent.Dispose(); } if (firedEvent != null){ firedEvent.Close(); firedEvent = null; } }
/// <summary> /// Create a WebRequest. This method will block if too many /// outstanding requests are pending or the throttle window /// threshold has been reached. /// </summary> /// <param name = "uri"></param> /// <returns></returns> public WebRequest Create(Uri uri) { lock (_throttleLock/*typeof(ThrottleLock)*/) { // note: we could use a list of WeakReferences and // may do so at a later date, but for now, this // works just fine as long as you call .Complete _outstandingRequests++; bool notifiedMaxPending = false; while (_outstandingRequests > MaxPendingRequests) { if (!notifiedMaxPending) { Log.Debug(string.Format("Waiting: pending requests {0}", _outstandingRequests)); } using (var throttleGate = new AutoResetEvent(false)) { throttleGate.WaitOne(100); throttleGate.Close(); } notifiedMaxPending = true; } if (_requestTimes.Count == ThrottleWindowCount) { // pull the earliest request of the bottom DateTimeOffset tail = _requestTimes.Dequeue(); // calculate the interval between now (head) and tail // to determine if we need to chill out for a few millisecons TimeSpan waitTime = (ThrottleWindowTime - (DateTimeOffset.UtcNow - tail)); if (waitTime.TotalMilliseconds > 0) { Log.Debug(string.Format("Waiting: " + waitTime + " to send " + uri.AbsoluteUri)); using (var throttleGate = new AutoResetEvent(false)) { throttleGate.WaitOne(waitTime); throttleGate.Close(); } } } // good to go. _requestTimes.Enqueue(DateTimeOffset.UtcNow); _dispatchedCount += 1; Log.Debug(string.Format("Dispatched #{0} : {1} ", _dispatchedCount, uri.AbsoluteUri)); return WebRequest.Create(uri); } }
/// <summary> /// Starts flow processing. /// </summary> internal void Start() { // Move processing to thread pool. AutoResetEvent startLock = new AutoResetEvent(false); ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state){ lock(m_pLock){ startLock.Set(); // TCP / TLS client, connect to remote end point. if(!m_IsServer && m_Transport != SIP_Transport.UDP){ try{ TCP_Client client = new TCP_Client(); client.Connect(m_pLocalEP,m_pRemoteEP,m_Transport == SIP_Transport.TLS); m_pTcpSession = client; BeginReadHeader(); } catch{ Dispose(); } } } })); startLock.WaitOne(); startLock.Close(); }