/// <summary> /// Event handler for the calibration OnEnd event of the gazetracker client /// which updates the status with the calibration quality rating. /// </summary> /// <param name="quality">The quality index of the calibration.</param> private void Calibration_OnEnd(int quality) { ThreadSafe.EnableDisableButton(this.RecordButton, true); this.DisplayMessage("Calibration Finished + Rating: " + quality); this.clientStatus.IsCalibrated = true; this.clientStatus.IsStreaming = false; }
/// <summary> /// Sets up calibration procedure and the tracking client /// and wires the events. Reads settings from file. /// </summary> protected override sealed void Initialize() { // Load alea tracker settings. if (File.Exists(this.SettingsFile)) { this.settings = this.DeserializeSettings(this.SettingsFile); } else { this.settings = new GazetrackerIPClientSetting(); this.SerializeSettings(this.settings, this.SettingsFile); } this.lastTime = 0; this.presentationScreenSize = Document.ActiveDocument.PresentationSize; this.launchButton.Click += this.LaunchButtonClick; this.statusUpdateTimer = new Timer { Interval = 100 }; this.statusUpdateTimer.Tick += this.StatusUpdateTimerTick; this.statusUpdateTimer.Start(); this.clientStatus.Reset(); ThreadSafe.EnableDisableButton(this.ConnectButton, false); }
static int Main(string[] args) { int rValue = 0; Thread[] threads = new Thread[100]; ThreadSafe tsi = new ThreadSafe(); string strIn = args[0]; Console.WriteLine("Creating threads"); for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(new ParameterizedThreadStart(tsi.ThreadWorker)); threads[i].Start(strIn); } tsi.Signal(); Console.WriteLine("Joining threads"); for(int i=0;i<threads.Length;i++) threads[i].Join(); // Build the expected string string strExpected = string.Empty; for(int i=0;i<threads.Length;i++) strExpected += tsi.Expected; if(tsi.Val == strExpected) rValue = 100; Console.WriteLine("Test Expected {0}, but found {1}", strExpected, tsi.Val); Console.WriteLine("Test {0}", rValue == 100 ? "Passed" : "Failed"); return rValue; }
private void Replace(string s, int index, HorizontalAlignment alignment) { int padding; float width; for (padding = 1; ; padding++) { width = graphics.MeasureString(new string (' ', padding) + s, listBox.Font, listBox.Width, stringFormatter).Width; if (width > listBox.DisplayRectangle.Width) { padding--; break; } } switch (alignment) { case HorizontalAlignment.Center: ThreadSafe.ItemsSetItem(listBox, index, new string (' ', padding / 2) + s); break; case HorizontalAlignment.Left: ThreadSafe.ItemsSetItem(listBox, index, s); ThreadSafe.ItemsAdd(listBox, s); break; case HorizontalAlignment.Right: ThreadSafe.ItemsSetItem(listBox, index, new string (' ', padding) + s); break; } ThreadSafe.SetTopIndex(listBox, ThreadSafe.GetItemsCount(listBox) - lines); }
public Map() { InitializeComponent(); // gMap gMapControl1.MapProvider = GMapProviders.BingHybridMap; PointLatLng point = new PointLatLng(49.394285, 2.711907); gMapControl1.Position = point; gMapControl1.MinZoom = 1; gMapControl1.MaxZoom = 21; gMapControl1.Zoom = 16; // Use UTC Proxy WebProxy proxy = new WebProxy("proxyweb.utc.fr", 3128); proxy.UseDefaultCredentials = true; GMapProvider.WebProxy = proxy; InitMapRoutes(); // Rectangle variables; pointListRectangle = new List <PointLatLng>(); pointListGeofence = new List <PointLatLng>(); initialRectanglePoint = new PointLatLng(); enableUpdate = true; waypointsMarkers = new List <GMapMarkerLabel>(); threadSafe = new ThreadSafe(); }
public void PrintInstruction(Instruction instruction, bool showKeycodes) { string s = instruction.TraceableText; Trace.Assert(s.Length <= symbolicWidth); s = s.PadLeft(symbolicWidth); if (showKeycodes) { s += instruction.Text.PadLeft(keycodeWidth); } switch (lastPrintedColumn) { case Column.Numeric: case Column.Step: { int count = ThreadSafe.ItemsCount(listBox); string lastItem = (string)ThreadSafe.ItemsGetItem(listBox, count - 1); lastItem = lastItem.Substring(0, lastItem.Length - symbolicWidth) + s; // We trim the leading spaces here because if we are showing the keycodes // there will be too many of them. Replace(lastItem.TrimStart(), count - 1, HorizontalAlignment.Right); break; } case Column.Instruction: { Append(s, HorizontalAlignment.Right); break; } } lastPrintedColumn = Column.Instruction; }
private void LoopRefreshInterval() { new ThreadSafe(() => { while (!_isStop) { var docs = _documentRepository.SelectAll(); var files = _fileRepository.SelectAll(); var links = _linkRepository.SelectAll(); PushReport(new Reports() { TotalDocDownloaded = docs.Count(i => i.SaveCompleted), TotalFilesDownloaded = files.Count(i => i.DownloadCompleted), TotalFilesFound = files.Count, TotalLinksDownloaded = links.Count(i => i.ParseCompleted), TotalLinksFound = links.Count, TotalLinksFail = links.Count(i => i.ParseFail), TotalFilesFail = files.Count(i => i.DownloadError) }); ThreadSafe.Sleep(_rnd.Next(5000, 10000)); } }).Start(); new ThreadSafe(() => { while (!_isStop) { RefreshInterval(this); ThreadSafe.Sleep(_rnd.Next(5000, 10000)); } }).Start(); }
public static int Bake(ref Keyframe[] keys, float frameRate, InterpolationMode mode = InterpolationMode.Auto) { var nativeKeys = new NativeArray <Keyframe>(keys, Allocator.Temp); float duration = keys[keys.Length - 1].time - keys[0].time; int frameCount = (int)math.ceil(frameRate * duration); var bakedKeys = new NativeArray <Keyframe>(frameCount, Allocator.Temp); ThreadSafe.Bake(nativeKeys, frameRate, bakedKeys, new SampleRange() { startFrameIndex = 0, numFrames = frameCount }); switch (mode) { case InterpolationMode.Linear: KeyframeUtilities.AlignTangentsLinear(bakedKeys); break; case InterpolationMode.Auto: KeyframeUtilities.AlignTangentsSmooth(bakedKeys); break; case InterpolationMode.ClampedAuto: KeyframeUtilities.AlignTangentsClamped(bakedKeys); break; default: throw new System.InvalidOperationException("Not Implemented"); } keys = bakedKeys.ToArray(); bakedKeys.Dispose(); return(frameCount); }
/// <summary> /// Configure the video window /// </summary> /// <param name="videoWindow">Interface of the video renderer</param> /// <param name="previewControl">Preview Control to draw into</param> private void ConfigureVideoWindow(IVideoWindow videoWindow, Control previewControl) { int hr; if (previewControl == null) { return; } // Set the output window hr = videoWindow.put_Owner(ThreadSafe.GetHandle(previewControl)); if (hr >= 0) // If there is video { // Set the window style hr = videoWindow.put_WindowStyle((WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings)); DsError.ThrowExceptionForHR(hr); // Make the window visible hr = videoWindow.put_Visible(OABool.True); DsError.ThrowExceptionForHR(hr); // Position the playing location Rectangle rc = ThreadSafe.GetClientRectangle(previewControl); hr = videoWindow.SetWindowPosition(0, 0, rc.Right, rc.Bottom); DsError.ThrowExceptionForHR(hr); } }
static int Main(string[] args) { int rValue = 0; Thread[] threads = new Thread[100]; ThreadSafe tsi = new ThreadSafe(); Console.WriteLine("Creating Threads"); for (int i = 0; i < threads.Length - 1; i++) { if (i % 2 == 0) threads[i] = new Thread(new ThreadStart(tsi.ThreadWorkerA)); else threads[i] = new Thread(new ThreadStart(tsi.ThreadWorkerB)); threads[i].Start(); } Console.WriteLine("Starting checker"); threads[threads.Length - 1] = new Thread(new ThreadStart(tsi.ThreadChecker)); threads[threads.Length - 1].Start(); tsi.Signal(); Console.WriteLine("Joining Threads"); for (int i = 0; i < threads.Length; i++) threads[i].Join(); if (tsi.Pass) rValue = 100; Console.WriteLine("Test {0}", rValue == 100 ? "Passed" : "Failed"); return rValue; }
static int Main(string[] args) { int rValue = 0; Thread[] threads = new Thread[100]; ThreadSafe tsi = new ThreadSafe(); KrisClass kcIn = new KrisClass(args[0]); Console.WriteLine("Creating threads"); for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(new ParameterizedThreadStart(tsi.ThreadWorker)); threads[i].Start(kcIn); } tsi.Signal(); Console.WriteLine("Joining threads"); for(int i=0;i<threads.Length;i++) threads[i].Join(); // Build the expected string KrisClass kcExpected = new KrisClass("hello world! "); for(int i=0;i<threads.Length * 100;i++) kcExpected = kcExpected + kcIn; if(kcExpected == tsi.GetValue) rValue = 100; Console.WriteLine("Test Expected {0}, but found {1}", kcExpected, tsi.GetValue); Console.WriteLine("Test {0}", rValue == 100 ? "Passed" : "Failed"); return rValue; }
public void PauseAndBlink(int count, int msPeriod) { string textWithPeriod = ThreadSafe.GetText(numericTextBox); string textWithoutPeriod = textWithPeriod.Replace(period, ' '); string [] texts = new String [] { textWithoutPeriod, textWithPeriod }; int interval = msPeriod / texts.Length; Mode = DisplayMode.Numeric; try { for (int i = 0; i < count; i++) { foreach (string text in texts) { ThreadSafe.SetText(numericTextBox, text); ThreadSafe.Update(this); // Most of the time the following call will just be equivalent to // Thread.Sleep. However, typing a key during PauseAndBlink causes the // current computation to stop. We detect this by calling WaitForKeystroke. if (WaitForKeystroke != null && WaitForKeystroke(interval)) { throw new Interrupt(); } } } } finally { // Restore the original text here to protect against exceptions. ThreadSafe.SetText(numericTextBox, textWithPeriod); } }
/////////////////////////////////////////////////////////////////////////////// // Public methods // /////////////////////////////////////////////////////////////////////////////// #region PUBLICMETHODS /// <summary> Begin capturing. </summary> public void Start() { if (this.mediaControl != null) { // Start the filter graph: begin capturing var hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); this.IsRunning = true; } if (this.videoWindow != null) { // Set owner var hr = this.videoWindow.put_Owner(ThreadSafe.GetHandle(this.previewWindow)); DsError.ThrowExceptionForHR(hr); // Set video window style hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren | WindowStyle.ClipSiblings); DsError.ThrowExceptionForHR(hr); // Set visible hr = this.videoWindow.put_Visible(OABool.True); DsError.ThrowExceptionForHR(hr); } }
protected override void OnResize(EventArgs e) { base.OnResize(e); int newLines = listBox.DisplayRectangle.Height / listBox.ItemHeight; if (newLines > lines) { for (int i = 1; i <= newLines - lines; i++) { ThreadSafe.ItemsInsert(listBox, 0, ""); } } else if (newLines < lines) { for (int i = 1; i <= lines - newLines; i++) { ThreadSafe.ItemsRemoveAt(listBox, 0); } } if (emptyLinesAtTop == lines) { emptyLinesAtTop = newLines; } lines = newLines; }
private void PrintAddress(string address) { string s = address.PadLeft(symbolicWidth - 1) + " "; switch (lastPrintedColumn) { case Column.Numeric: { int count = ThreadSafe.ItemsCount(listBox); string lastItem = (string)ThreadSafe.ItemsGetItem(listBox, count - 1); lastItem = lastItem.Substring(0, lastItem.Length - symbolicWidth) + s; Replace(lastItem, count - 1, HorizontalAlignment.Right); break; } case Column.Instruction: { Append(s, HorizontalAlignment.Right); break; } case Column.Step: { Trace.Assert(false); break; } } lastPrintedColumn = Column.Instruction; }
void sim_OnSimulationComplete(Simulation sim, double fRunTimeMS) { ThreadSafe.Do(this, () => { lblProgress.Text = "Plotting results"; }); //save last simulation _simLast = sim; _fRunTimeMS = fRunTimeMS; double[] x = new double[sim.N / cfg.PlotStep]; for (int i = 0; i < sim.N / cfg.PlotStep; i++) { x[i] = (double)i * cfg.PlotTimeStep; } for (int i = 0; i < cfg.PlotMap.Length; i++) { int nGraph = 0, nChannel = 0, nSim = -1, nValIndex = 0; string[] sTmp; bool b = true; sTmp = cfg.PlotMap[i][0].Split('.'); if (sTmp.Length == 2) { b &= int.TryParse(sTmp[0], out nGraph); b &= int.TryParse(sTmp[1], out nChannel); } else { b = false; } sTmp = cfg.PlotMap[i][1].Split('.'); if (sTmp.Length == 2) { b &= int.TryParse(sTmp[0], out nSim); b &= int.TryParse(sTmp[1].Substring(1), out nValIndex); } else { b = false; } if (b) { if (nSim == sim.Index) { switch (sTmp[1][0]) { case 'x': gr[nGraph].SetXY(nChannel, x, sim.GetState(nValIndex, cfg.PlotStep, -1000, 1000)); break; case 'u': gr[nGraph].SetXY(nChannel, x, sim.GetInput(nValIndex, cfg.PlotStep, -1000, 1000)); break; case 'y': gr[nGraph].SetXY(nChannel, x, sim.GetMeasurment(nValIndex, cfg.PlotStep, -1000, 1000)); break; } } } } }
public LocationManagerMock(IGeoPoint point) { this.point = point; this.timer = new Timer(_ => ping()); this.interval = new ThreadSafe <int>(Timeout.Infinite); this.listener = new ThreadSafe <ILocationListener>(); this.provider = new ThreadSafe <string>(); }
/// <summary> /// Event handler for the calibration OnEnd event of the haytham tracker client /// which updates the status with the calibration quality rating. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The <see cref="EventArgs"/> instance containing the event data. /// </param> private void CalibrationFinished(object sender, EventArgs e) { ThreadSafe.EnableDisableButton(this.RecordButton, true); this.DisplayMessage("Calibration Finished"); this.clientStatus = this.clientStatus | HaythamStatus.IsCalibrated; // Show track status control ThreadSafe.ShowHideSplitContainerPanel(this.trackControlsSplitContainer, true, false); ThreadSafe.ShowHideSplitContainerPanel(this.trackControlsSplitContainer, false, true); }
private void Box_GotFocus(object sender, EventArgs e) { IsInput = true; Box.BackColor = ColorUtil.Blend(BgColor, Color.SteelBlue); Timer.AddTrigger(20, () => { var txt = ThreadSafe.GetTextControl(Box); ThreadSafe.SetSelectTextBox(Box, 0, txt.Length); }); }
public void UsageTest() { var tsf = new ThreadSafe<MyClass>(); tsf.Execute(x => x.Increment()); Assert.IsNotNull(tsf.InnerInstance); Assert.AreEqual(1, tsf.InnerInstance.Counter); tsf.Execute(x => x.Increment()); Assert.IsNotNull(tsf.InnerInstance); Assert.AreEqual(2, tsf.InnerInstance.Counter); }
public void Dispose() { for (int i = 0; i < 30; i++) { if (!_isStop) { ThreadSafe.Sleep(1000); } } }
public void Advance() { if (emptyLinesAtTop > 0) { ThreadSafe.ItemsRemoveAt(listBox, 0); emptyLinesAtTop--; } ThreadSafe.ItemsAdd(listBox, ""); ThreadSafe.SetTopIndex(listBox, ThreadSafe.GetItemsCount(listBox) - lines); lastPrintedColumn = Column.Instruction; }
/// <summary> /// Reads settings from file. Then checks for existing haytham servers on /// the network to set the IP in the settings. /// </summary> protected override sealed void Initialize() { // Load haytham tracker settings. if (File.Exists(this.SettingsFile)) { this.settings = this.DeserializeSettings(this.SettingsFile); } else { this.settings = new HaythamSetting(); this.SerializeSettings(this.settings, this.SettingsFile); } Task.Factory.StartNew( () => { // find haytham hosts on network Uri hostUri = Client.getActiveHosts().FirstOrDefault(); while (hostUri == null) { // wait 5 seconds before next try Thread.Sleep(5000); // it has 2seconds timeout hostUri = Client.getActiveHosts().FirstOrDefault(); } // show IPv4 address if exists IPAddress server = Dns.GetHostAddresses(hostUri.DnsSafeHost) .FirstOrDefault(adr => adr.AddressFamily == AddressFamily.InterNetwork); if (server != null) { this.settings.HaythamServerIPAddress = server.ToString(); } }); this.lastTime = 0; this.launchButton.Click += this.LaunchButtonClick; this.statusUpdateTimer = new Timer { Interval = 100 }; this.statusUpdateTimer.Tick += this.StatusUpdateTimerTick; this.statusUpdateTimer.Start(); this.clientStatus = 0; this.trackControlsSplitContainer.Panel1Collapsed = false; this.trackControlsSplitContainer.Panel2Collapsed = true; ThreadSafe.EnableDisableButton(this.ConnectButton, false); }
static int Main(string[] args) { int rValue = 0; Thread[] threads = new Thread[100]; ThreadSafe tsi = new ThreadSafe(); Console.WriteLine("Creating threads"); for (int i = 0; i < threads.Length - 1; i++) { if (i % 2 == 0) { threads[i] = new Thread(new ParameterizedThreadStart(tsi.ThreadWorkerA)); } else { threads[i] = new Thread(new ParameterizedThreadStart(tsi.ThreadWorkerB)); } threads[i].Start(args); } Console.WriteLine("Starting checker"); threads[threads.Length - 1] = new Thread(new ThreadStart(tsi.ThreadChecker)); threads[threads.Length - 1].Start(); //Added to prevent races where Checker does not get to Wait before ManualEvent is Set while (tsi.ThreadCount < 100) { Thread.Sleep(100); } Thread.Sleep(100); tsi.Signal(); Console.WriteLine("Joining threads"); for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } if (tsi.Pass) { rValue = 100; } Console.WriteLine("Test {0}", rValue == 100 ? "Passed" : "Failed"); return(rValue); }
/// <summary> /// 文字列からパラメータを解析・実行する /// </summary> /// <param name="param"></param> public override void ParseParameter(string param) { var ss = param.Split(new char[] { ',' }); foreach (var s in ss) { var s2 = s.Trim(); // インターロックグループ var id = s2.IndexOf("("); if (id >= 0) { var gr = s2.Substring(id + 1); _interlockGroup = gr.Substring(0, gr.Length - 2); var fcs = (IList)_interlockGroups[_interlockGroup]; if (fcs == null) { _interlockGroups[_interlockGroup] = fcs = new ArrayList(); } fcs.Add(this); s2 = s2.Substring(0, id) + "]"; } // チェックボタンのイベント登録 if (s2.StartsWith("[")) { var s3 = s2.Substring(1, s2.Length - 2); var sss = s3.Split(new char[] { '=' }); s2 = sss[0]; if (sss.Length >= 2) { if (Const.IsFalse(sss[1])) { _isOn = false; } } _initialState = _isOn; _checkBox = (System.Windows.Forms.CheckBox)GetControl(s2); if (_checkBox != null) { AddTrigger(_checkBox, "Click", new EventHandler(onClickCheck)); ThreadSafe.SetChecked(_checkBox, _isOn); ThreadSafe.SetEnabled(_checkBox, _canStart); } } } _isNoToken = true; Finalizers.Add(new FinalizeManager.Finalize(resetSwitch)); }
/// <summary> /// The ClientConnectionChanged event handler for the gazetracker /// client. Updates UI. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="success">True if connection could be established, otherwise false.</param> private void ClientClientConnectionChanged(object sender, bool success) { if (success) { ThreadSafe.EnableDisableButton(this.SubjectButton, true); this.clientStatus.IsConnected = true; } else { this.clientStatus.Reset(); this.ConnectButton.BackColor = Color.Transparent; ThreadSafe.EnableDisableButton(this.SubjectButton, false); ThreadSafe.EnableDisableButton(this.RecordButton, false); } }
static void Main(string[] args) { //BasicThread BT = new BasicThread(); //BT.ThreadInfo(); // BT.TaskDemo(); //BT.ThreadStartLock(); //BT.MutexLockDemo(); //BT.SemaphoreDemo(); ThreadSafe TS = new ThreadSafe(); TS.ListSafety(); Console.ReadLine(); }
/// <summary> /// Overridden <see cref="Control.Click"/> event handler for the /// <see cref="Button"/> subject button. /// Calls the base class and enables the record button, /// because this tracker has done its calibration externally /// </summary> /// <param name="sender"> /// Source of the event. /// </param> /// <param name="e"> /// An empty <see cref="EventArgs"/>. /// </param> protected override void BtnSubjectNameClick(object sender, EventArgs e) { base.BtnSubjectNameClick(sender, e); // Activate the calibrate button // if the subject name is OK if (!Queries.CheckDatabaseForExistingSubject(this.SubjectButton.Text)) { //this.CalibrateButton.Enabled = true; this.DisplayMessage( "Please ensure the haytham tracker has a camera stream running and is tracking the eye successfully!"); } ThreadSafe.EnableDisableButton(this.RecordButton, true); }
public void ThreadSafeAdd() { int nrIterations = 100000; Calculation c = new Calculation(); dynamic ts = new ThreadSafe(c); List <Task> tasks = new List <Task>(); for (int i = 0; i < nrIterations; i++) { var t = new Task <int>(() => ts.Add()); tasks.Add(t); } tasks.ForEach(t => t.Start()); Task.WaitAll(tasks.ToArray()); Assert.AreEqual(nrIterations, c.i); }
public void PauseAndAcceptKeystrokes(int ms) { Mode = DisplayMode.Numeric; ThreadSafe.Update(this); while (WaitForKeystroke != null & WaitForKeystroke(ms)) { if (AcceptKeystroke != null) { AcceptKeystroke(); } ThreadSafe.Update(this); } if (CompleteKeystrokes != null) { CompleteKeystrokes(); } }
private void LoopThreadDataMaping() { new ThreadSafe(() => { while (!_isStop) { var link = RepositoryContainer.LinkRepository.GetLinkToExtract(); if (link != null) { IDataMaping dataMaping = new DataMapingCommon(); dataMaping.DataMapingComplete += OnDataMapingComplete; dataMaping.Init(_config); dataMaping.Do(link); } ThreadSafe.Sleep(_rnd.Next(1000, 10000)); } }).Start(); }
private void ProccessGrabber_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { ThreadSafe.Invoke(this, GetAllProc, true, ThreadSafe.InvokeProperty.Enabled, ThreadSafe.InvokeMethod.SET); ThreadSafe.Invoke(this, StartMonitoring, true, ThreadSafe.InvokeProperty.Enabled, ThreadSafe.InvokeMethod.SET); if (e.Result.ToString().StartsWith("ENOENT - Proccess Not Found")) { GC.Collect(); ProccessGrabber.RunWorkerAsync("catch-start --retry"); } else if (e.Result.ToString() == "SUCCESS !") { ThreadSafe.Invoke(this, label1, String.Empty, ThreadSafe.InvokeProperty.Text, ThreadSafe.InvokeMethod.SET); TaskBarFlash.Flash(this); GC.Collect(); return; } }
private void UpdateBoxValue() { if (!IsInput && !IsFormClosing) { try { var cpos = Hot.TimelineParts.GetCdPos(TarPane, TarPane.GetPaneRect().LT); var tartime = Hot.FirstSpeech + TimeSpan.FromSeconds(cpos.X); ThreadSafe.SetTextControl(Box, lastTimeText = tartime.ToString(TimeUtil.FormatHMS)); } catch { } } if (!IsFormClosing) { Timer.AddTrigger(500, UpdateBoxValue); } }
static int Main(string[] args) { int rValue = 0; Thread[] threads = new Thread[100]; ThreadSafe tsi = new ThreadSafe(); Console.WriteLine("Creating threads"); for (int i = 0; i < threads.Length - 1; i++) { if (i % 2 == 0) threads[i] = new Thread(new ParameterizedThreadStart(tsi.ThreadWorkerA)); else threads[i] = new Thread(new ParameterizedThreadStart(tsi.ThreadWorkerB)); threads[i].Start(args); } Console.WriteLine("Starting checker"); threads[threads.Length - 1] = new Thread(new ThreadStart(tsi.ThreadChecker)); threads[threads.Length - 1].Start(); //Added to prevent races where Checker does not get to Wait before ManualEvent is Set while(tsi.ThreadCount < 100) { Thread.Sleep(100); } Thread.Sleep(100); tsi.Signal(); Console.WriteLine("Joining threads"); for (int i = 0; i < threads.Length; i++) threads[i].Join(); if (tsi.Pass) rValue = 100; Console.WriteLine("Test {0}", rValue == 100 ? "Passed" : "Failed"); return rValue; }
void Add(Dictionary<uint, CorMethodDef> dict, ThreadSafe.IList<MethodDef> methods, uint token) { var cmd = Lookup(dict, token); if (cmd == null || methods.Contains(cmd)) return; methods.Add(cmd); }
internal void InitializeEvent(CorEventDef evt, out MethodDef addMethod, out MethodDef invokeMethod, out MethodDef removeMethod, out ThreadSafe.IList<MethodDef> otherMethods) { addMethod = null; invokeMethod = null; removeMethod = null; otherMethods = ThreadSafeListCreator.Create<MethodDef>(); var mdi = readerModule.MetaDataImport; uint token = evt.OriginalToken.Raw; uint addToken, removeToken, fireToken; MDAPI.GetEventAddRemoveFireTokens(mdi, token, out addToken, out removeToken, out fireToken); var otherTokens = MDAPI.GetEventOtherMethodTokens(mdi, token); var dict = CreateMethodDict(); addMethod = Lookup(dict, addToken); invokeMethod = Lookup(dict, fireToken); removeMethod = Lookup(dict, removeToken); foreach (uint otherToken in otherTokens) Add(dict, otherMethods, otherToken); }
internal void InitializeProperty(CorPropertyDef prop, out ThreadSafe.IList<MethodDef> getMethods, out ThreadSafe.IList<MethodDef> setMethods, out ThreadSafe.IList<MethodDef> otherMethods) { getMethods = ThreadSafeListCreator.Create<MethodDef>(); setMethods = ThreadSafeListCreator.Create<MethodDef>(); otherMethods = ThreadSafeListCreator.Create<MethodDef>(); if (prop == null) return; var mdi = readerModule.MetaDataImport; uint token = prop.OriginalToken.Raw; uint getToken, setToken; MDAPI.GetPropertyGetterSetter(mdi, token, out getToken, out setToken); var otherTokens = MDAPI.GetPropertyOtherMethodTokens(mdi, token); var dict = CreateMethodDict(); Add(dict, getMethods, getToken); Add(dict, setMethods, setToken); foreach (uint otherToken in otherTokens) Add(dict, otherMethods, otherToken); }
bool ContainsGenericParameter(ThreadSafe.IList<TypeSig> types) { if (types == null) return false; if (!recursionCounter.Increment()) return false; bool res = false; foreach (var type in types.GetSafeEnumerable()) { if (ContainsGenericParameter(type)) { res = true; break; } } recursionCounter.Decrement(); return res; }