public IActionResult TurnReset([FromQuery] string gameId, [FromQuery] string color) { System.Threading.Semaphore s = new System.Threading.Semaphore(1, 1, "COPS"); s.WaitOne(); try { if (gameId == null) { return(BadRequest()); } MakeCertainGameExists(gameId); var board = VisualBoardStore.GameBoard(gameId + "SNAPSHOT"); VisualBoardStore.KillBoard(gameId); var newboard = new Dictionary <string, string>(); foreach (var item in board) { newboard.Add(item.Key, item.Value); } VisualBoardStore.AddBoard(gameId, newboard); // overwrite it Response.Headers.Add("Access-Control-Allow-Origin", "*"); return(Ok()); } finally { s.Release(); } }
public static void Main() { //const string SemaphoreName = ".NET TopmostLaunture #054702 (C#)"; string SemaphoreName = ".NET TopmostLaunture " + System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("\\", "/"); bool createdNew; // Semaphoreクラスのインスタンスを生成し、アプリケーション終了まで保持する using (var semaphore = new System.Threading.Semaphore(1, 1, SemaphoreName, out createdNew)) { if (!createdNew) { // 他のプロセスが先にセマフォを作っていた return; // プログラム終了 } // アプリケーション起動 cw_onscl.App app = new cw_onscl.App(); app.InitializeComponent(); //このタイミング辺りで以下のメソッドが働く //protected override void OnSourceInitialized(EventArgs e) app.Run(); } // Semaphoreクラスのインスタンスを破棄 }
public IActionResult TurnConcluded([FromQuery] string gameId, [FromQuery] string color) { System.Threading.Semaphore s = new System.Threading.Semaphore(1, 1, "COPS"); s.WaitOne(); try { if (gameId == null) { return(BadRequest()); } MakeCertainGameExists(gameId); var board = VisualBoardStore.GameBoard(gameId); // just store that last board state in case someone hits turn reset. if (VisualBoardStore.ContainsGame(gameId + "SNAPSHOT")) { VisualBoardStore.KillBoard(gameId + "SNAPSHOT"); // if any... } var newboard = new Dictionary <string, string>(); foreach (var item in board) { newboard.Add(item.Key, item.Value); } VisualBoardStore.AddBoard(gameId + "SNAPSHOT", newboard); Response.Headers.Add("Access-Control-Allow-Origin", "*"); return(Ok()); } finally { s.Release(); } }
internal Message(Delegate d, params object[] args) { dg = d; this.args = args; principal = System.Threading.Thread.CurrentPrincipal; sem = new System.Threading.Semaphore(0, 1); }
// Schrum: This method executes a single time step. It is called repeatedly during an evaluation override protected bool runEnvironment(Environment e, instance_pack ip, System.Threading.Semaphore sem) { // Schrum: ip is null initially, but should not be after first step if (ip != null) { //Console.WriteLine("Update ip"); // Make sure enemies have accurate reference for evolved bot foreach (EnemyRobot r in enemies) { r.evolved = ip.robots[0]; } } //else Console.WriteLine("IP NULL!"); // Then run the environment as normal bool result = base.runEnvironment(e, ip, sem); // Schrum: To avoid a memory leak, remove references to the evolved bot from the enemies if (ip != null) // Only do when ip is not null { // ip is used during evolution, but not during visual post-eval foreach (EnemyRobot r in enemies) { r.evolved = null; } } return(result); }
public frmDockedMain(string[] args) { InitializeComponent(); loadCombos(); this.loadingSong = false; this.songPlayer = new Player(); this.songPlayer.NextLine += new Player.NextLineEventHandler(songPlayer_NextLine); this.songPlayer.SongFinished += new EventHandler(songPlayer_SongFinished); this.songPlayer.CurrentTempoChanged += songPlayer_CurrentTempoChanged; initializeSong(); bindControls(); this.lboxPatterns.SelectedIndex = 0; this.cmbOctavaBase.SelectedIndex = 1; this.patEditor.EditionIncrement = 1; this.patEditor.HighlightRange = 4; this.patEditor.DelayDecrement = 2; this.cboStereo.SelectedIndex = 0; this.txtResalte.Text = "4"; if (args.Length > 0) { loadSongFromFile(args[0]); } asyncThreadSemaphore = new System.Threading.Semaphore(1, 1); if (Properties.Settings.Default.ShowSplash) { ApplicationState.Instance.SplashScreen.FadeOut(); } }
/// <summary> /// Instantiates IpcEventWriter by initializing MmfWriter. /// </summary> /// <param name="applicationName">Application name to use in MmfWriter</param> /// <param name="ipcType">Identifies and authenticates data for memory mapped file</param> /// <param name="ipcEventMessageLength">Length of data segment</param> /// <param name="ignoreIpcExceptions">True if write exceptions in MmfWriter should be handled by MmfWriter; false if they should be returned.</param> public IpcEventWriter(string applicationName, string ipcType, int ipcEventMessageLength, Niawa.Utilities.UtilsServiceBus utilsBus, bool ignoreIpcExceptions) { try { _applicationName = applicationName; _ipcType = ipcType; _ipcEventMessageLength = ipcEventMessageLength; _ignoreIpcExceptions = ignoreIpcExceptions; //initialize serial ID generator id = utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_IPC_EVENT); //initialize MMF writer mmfWriter = new Niawa.IpcController.MmfBufferedWriter(_ipcType, _ipcEventMessageLength, utilsBus, _ignoreIpcExceptions); lockSection = new System.Threading.Semaphore(1, 1); } catch (Exception ex) { logger.Error("[IpcEventWriter " + _ipcType + "] Caught exception during IpcEventWriter instantiate: " + ex.Message, ex); if (ignoreIpcExceptions) { } else throw ex; } }
public ZeroEvenOdd(int n) { this.n = n; this.signalZero = new System.Threading.Semaphore(1, 1); this.signalEven = new System.Threading.Semaphore(0, 1); this.signalOdd = new System.Threading.Semaphore(0, 1); }
public IActionResult Back([FromQuery] string gameId) { System.Threading.Semaphore s = new System.Threading.Semaphore(1, 1, "COPS"); s.WaitOne(); try { if (gameId == null) { return(BadRequest()); } MakeCertainGameExists(gameId); for (int iStep = 1000; iStep > 99; iStep--) { if (VisualBoardStore.ContainsGame(gameId + iStep.ToString())) { // when the snapshot board matches the current board, we go one past that one... var snapBoard = VisualBoardStore.GameBoard(gameId + iStep); var curBoard = VisualBoardStore.GameBoard(gameId); if (NoDifferences(curBoard, snapBoard)) { iStep--; if (iStep == 99) { break; } var newboard = FreshCopyOf(VisualBoardStore.GameBoard(gameId + iStep.ToString())); VisualBoardStore.KillBoard(gameId); VisualBoardStore.AddBoard(gameId, newboard); break; } } } return(Ok()); } finally { s.Release(); } }
public IActionResult TurnReset([FromQuery] string gameId, [FromQuery] string color) { Response.Headers.Add("Access-Control-Allow-Origin", "*"); System.Threading.Semaphore s = new System.Threading.Semaphore(1, 1, "COPS"); s.WaitOne(); try { if (gameId == null || color == null) { return(BadRequest()); } MakeCertainGameExists(gameId); string highestGameSnapshot = null; for (int iStep = 100; iStep < 1000; iStep++) { if (VisualBoardStore.ContainsGame(gameId + iStep.ToString())) { highestGameSnapshot = gameId + iStep.ToString(); continue; } // Set the board to the highest game snapshot we have. var board = VisualBoardStore.GameBoard(highestGameSnapshot); var newboard = FreshCopyOf(board); VisualBoardStore.KillBoard(gameId); VisualBoardStore.AddBoard(gameId, newboard); // overwrite it } return(Ok()); } finally { s.Release(); } }
/// <summary> /// 开始和指定端口连接 /// </summary> /// <param name="port"></param> public void Start(int port) { this.acceptClients = new System.Threading.Semaphore(this.maxClient, this.maxClient); try { this.ServerIPV4.Bind((EndPoint) new IPEndPoint(IPAddress.Any, port)); this.ServerIPV6.Bind((EndPoint) new IPEndPoint(IPAddress.IPv6Any, port)); //挂起的连接队列的最大长度为10 this.ServerIPV4.Listen(10); ////挂起的连接队列的最大长度为10 this.ServerIPV6.Listen(10); //ipv4 开始接受,其中waitone 即是一般的new Thread + thread.start(); StartAccept((SocketAsyncEventArgs)null); //ipv6 开始接受,传null StartAcceptV6((SocketAsyncEventArgs)null); } catch (Exception ex) { if (DebugMessage.Error == null) { return; } DebugMessage.Error((object)ex.Message); } }
public void Stop() { _Stop = true; _LastProgressTime = DateTime.Now; _StoppedSignal = new System.Threading.Semaphore(1, 1); _StoppedSignal.WaitOne(); }
static void Main(string[] args) { semaphore = new System.Threading.Semaphore(2, 2); DELG d = (state) => { semaphore.WaitOne(); for (int i = 0; i < 3; i++) { string name_thread = (string)state; Console.WriteLine("Thread -> {0} -- Etat -> {1}", name_thread, simu_cnx_db.ToString()); System.Threading.Thread.Sleep(2000); } semaphore.Release(); }; System.Threading.Thread t1 = new System.Threading.Thread(d.Invoke); System.Threading.Thread t2 = new System.Threading.Thread(d.Invoke); System.Threading.Thread t3 = new System.Threading.Thread(d.Invoke); t1.Start(((object)("T1"))); t2.Start(((object)("T2"))); t3.Start(((object)("T3"))); Console.Read(); }
public static void Main(string[] args) { var sem = new System.Threading.Semaphore(0, 1); Run(sem, args); sem.WaitOne(); }
public void Start() { if (thread != null) throw new Exception("Cannot start service twice."); semaphore = new System.Threading.Semaphore(0, 1); thread = new System.Threading.Thread(new System.Threading.ThreadStart(InternalMain)); thread.Start(); }
public InvokeActionWrapper(Control control) { _control = control; _control.HandleCreated += _control_HandleCreated; _semaphore = new System.Threading.Semaphore(0, short.MaxValue); _actionCollection = new Dictionary <Control, List <Action> >(); _actionCollection[control] = new List <Action>(); }
private void init() { mHostList = new ArrayList(); mPortList = new ArrayList(); hostport_semaphore = new System.Threading.Semaphore(1, 1); //String strconn = "Data Source="+AppDomain.CurrentDomain.BaseDirectory + "ntp_servers.db"; //@"Data Source=C:\Users\황세현삼성놋9\Desktop\TimeSync\TimeSync\bin\Debug\ntp_servers.db"; sqlite_conn = new NTPServersManager().getConnection(); //new SQLiteConnection(strconn); }
/// <summary> /// /// </summary> public UtilsServiceBus() { lockSection = new System.Threading.Semaphore(1, 1); internalLockSection = new System.Threading.Semaphore(1, 1); idGenerator = new IdGeneratorUtils(); valueRegistry = new SortedList<string, List<string>>(); }
public Utilidades(MySqlConnection conexion) { GestorBDCD40 = new GestorBaseDatos(conexion); if (SemaforoSectorizacionSacta == null) { SemaforoSectorizacionSacta = new System.Threading.Semaphore(1, 1); } }
public bool Stop() { if (this.synchronizer != null) { this.synchronizer.Close(); this.synchronizer = null; } return(true); }
/// <summary> /// NIM客户端注销/退出,同步方法 /// </summary> /// <param name="logoutType"></param> /// <param name="waitSeconds"></param> public static void Logout(NIMLogoutType logoutType, int waitSeconds = 10) { System.Threading.Semaphore semaphore = new System.Threading.Semaphore(0, 1); NIM.ClientAPI.Logout(logoutType, (r) => { semaphore.Release(); }); semaphore.WaitOne(TimeSpan.FromSeconds(waitSeconds)); }
public IActionResult TurnConcluded([FromQuery] string gameId, [FromQuery] string color) { Response.Headers.Add("Access-Control-Allow-Origin", "*"); System.Threading.Semaphore s = new System.Threading.Semaphore(1, 1, "COPS"); s.WaitOne(); try { if (gameId == null || color == null) { return(BadRequest()); } MakeCertainGameExists(gameId); var board = VisualBoardStore.GameBoard(gameId); // Some day this move will be validated, but for now, I just find the next sequential snapshot slot and store the board there. // just store that last board state in case someone hits turn reset. var newboard = FreshCopyOf(board); for (int iStep = 100; iStep < 1000; iStep++) { if (VisualBoardStore.ContainsGame(gameId + iStep.ToString())) { continue; } // ok we found this game snapshot name VisualBoardStore.AddBoard(gameId + iStep.ToString(), newboard); break; } Dictionary <string, string> boardHues = new Dictionary <string, string>(); foreach (var pos in board.Keys) { if (pos == "n0_n0") { boardHues.Add(pos, "0,0,0,1.0"); // black center } else { boardHues.Add(pos, "128,128,128,0.9"); // gray by default } } HexC.Program.LightUpWillsBoard(board, boardHues, null); VisualBoardStore.ReplaceTeamHues(gameId, "black", boardHues); VisualBoardStore.ReplaceTeamHues(gameId, "white", boardHues); VisualBoardStore.ReplaceTeamHues(gameId, "tan", boardHues); // Store the color of the clicker party. VisualBoardStore.LastReportedTurnEnd(gameId, color); return(Ok()); } finally { s.Release(); } }
public Semaphore() { s1 = new System.Threading.Semaphore(1, 5); s2 = new System.Threading.Semaphore(1, 5); // <= 0 DENY >0 APPROVE // Release +1 WaitOne -1 //OR x // == 0 APPROVE >0 DENY //RELEASE -1 WAITONE +1 }
public SimpleLock(bool consoleLog = false) { handle = new System.Threading.Semaphore(1, 1); id = Convert.ToUInt32(new Random().Next(0, 999999)); ConsoleLog = consoleLog; if (ConsoleLog) { Console.WriteLine("Lock created id " + id); } }
public void Start() { if (thread != null) { throw new Exception("Cannot start service twice."); } semaphore = new System.Threading.Semaphore(0, 1); thread = new System.Threading.Thread(new System.Threading.ThreadStart(InternalMain)); thread.Start(); }
void Method() { System.Threading.Semaphore semaphore = new System.Threading.Semaphore(1, 1); semaphore.WaitOne(); // execute semaphore.Release(1); }
public void Dispose() { if (_useContexts != null) { _useContexts.Dispose(); _useContexts = null; } if (DataSet != null) { DataSet.Dispose(); DataSet = null; } }
public bool Start() { this.configurationService = this.manager.ConfigurationService; this.sipService = this.manager.SipService; this.contactService = this.manager.ContactService; #if !ASYNCHRONOUSLY this.synchronizer = new System.Threading.Semaphore(0, 1); #endif return(true); }
/// <summary> /// Instantiates a IpcTreeWebWindowTreeItem. This item contains data for a tree item /// in the tree model, as well as functionality to support the current view (cached status /// and events received from IPC Reader). /// </summary> /// <param name="nodeText"></param> /// <param name="ipcType"></param> /// <param name="nodeID"></param> /// <param name="parentNodeID"></param> public IpcTreeWebWindowTreeItem(string nodeText, string ipcType, string nodeID, string parentNodeID, IpcTreeWebWindow window, IpcTreeWebWindowTreeModel treeModel) { _ipcType = ipcType; _nodeText = nodeText; _nodeID = nodeID; _parentNodeID = parentNodeID; lockSection = new System.Threading.Semaphore(1, 1); _window = window; _browser = _window.WebBrowser1; _treeModel = treeModel; }
private void Fractal_Load(object sender, EventArgs e) { Graphics GraphObj; // Setup persistent image for picture box and set background to white ImageBitmap = new Bitmap(picImage.ClientRectangle.Width, picImage.ClientRectangle.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); GraphObj = Graphics.FromImage(ImageBitmap); GraphObj.Clear(System.Drawing.Color.White); GraphObj.Dispose(); ImageLock = new System.Threading.Semaphore(1, 1); // Create semaphore }
public void SetMaxItem(int maxItems) { lock (this) { if (_freeContexts.Count != _contexts.Count) { throw new Exception("ContextManager can't set MaxItem while contexts running"); } if (_useContexts != null) { _useContexts.Dispose(); } _useContexts = null; _useContexts = new System.Threading.Semaphore(maxItems, maxItems); } }
/// <summary> /// 登录结果处理 /// </summary> /// <param name="result"></param> private static void HandleLoginResult(NIM.NIMLoginResult result) { if (result.LoginStep == NIM.NIMLoginStep.kNIMLoginStepLogin) { //登录成功 if (result.Code == NIM.ResponseCode.kNIMResSuccess) { if (!NIM.VChatAPI.Init()) { NimUtility.Log.Error("音视频通话功能初始化失败"); LogHelper.WriteError("音视频通话功能初始化失败"); ErrorMsg = "音视频通话功能初始化失败"; IsInit = false; #region 登出->清理API System.Threading.Semaphore s = new System.Threading.Semaphore(0, 1); Logout(NIMLogoutType.kNIMLogoutAppExit, (r) => { s.Release(); }); //需要logout执行完才能退出程序 s.WaitOne(TimeSpan.FromSeconds(10)); ClientAPI.Cleanup(); #endregion return; } IsInit = true; LogHelper.WriteDebug("音视频通话功能初始化成功."); InitVChatInfo(); } else { NimUtility.Log.Error("音视频通话API登录失败"); LogHelper.WriteError("音视频通话API登录失败"); ErrorMsg = "音视频通话API登录失败"; IsInit = false; #region 登出->清理API System.Threading.Semaphore s = new System.Threading.Semaphore(0, 1); Logout(NIMLogoutType.kNIMLogoutChangeAccout, (r) => { s.Release(); }); //需要logout执行完才能退出程序 s.WaitOne(TimeSpan.FromSeconds(10)); ClientAPI.Cleanup(); #endregion } } }
public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); searching = new System.Threading.Semaphore(1, 1); stdOut.DeactivateDebug(); stdOut.SetInterface(StdOutInterfaces.WindowsForm); EDOLLHandler.Start(false); log = new M3SFrameLog(); // // TODO: Add constructor code after the InitializeComponent() call. // }
public IActionResult Selected([FromQuery] string gameId, [FromQuery] string loc, [FromQuery] string color) { Response.Headers.Add("Access-Control-Allow-Origin", "*"); System.Threading.Semaphore s = new System.Threading.Semaphore(1, 1, "COPS"); s.WaitOne(); try { if (gameId == null) { return(BadRequest()); } string json = InternalSelected(gameId, loc, color); return(Ok(json)); } finally { s.Release(); } }
public IActionResult Selected([FromQuery] string gameId, [FromQuery] string loc, [FromQuery] string color) { System.Threading.Semaphore s = new System.Threading.Semaphore(1, 1, "COPS"); s.WaitOne(); try { if (gameId == null) { return(BadRequest()); } MakeCertainGameExists(gameId); var board = VisualBoardStore.GameBoard(gameId); Dictionary <string, string> boardHues = new Dictionary <string, string>(); foreach (var pos in board.Keys) { if (pos == "n0_n0") { boardHues.Add(pos, "0,0,0,1.0"); // black center } else { boardHues.Add(pos, "128,128,128,0.9"); // gray by default } } HexC.Program.LightUpWillsBoard(board, boardHues, loc); VisualBoardStore.ReplaceHues(gameId, color, boardHues); string json = ""; json = "["; foreach (var spot in board) { json += "{\"loc\":\"" + spot.Key; json += "\",\"tok\":\"" + spot.Value; json += "\",\"hue\":\"" + boardHues[spot.Key]; // (spot.Key[0] == 'P' ? "0,255,0,0.7" : "255,0,0,0.7"); json += "\"},"; } json = json.Substring(0, json.Length - 1); json += "]"; //Response.Headers.Add("Access-Control-Allow-Origin", "https://hexagonalchess.online"); Response.Headers.Add("Access-Control-Allow-Origin", "*"); return(Ok(json)); } finally { s.Release(); } }
public void CreatedEventTest() { IRemoteCache<string, string> cache = remoteManager.GetCache<string, string>(); cache.Clear(); Event.ClientListener<string, string> cl = new Event.ClientListener<string, string>(); cl.filterFactoryName = ""; cl.converterFactoryName = ""; cl.addListener(createdEventAction); createdEventCounter = 0; createdSemaphore = new System.Threading.Semaphore(0, 1); cache.addClientListener(cl, new string[] { }, new string[] { }, null); Assert.AreEqual(0, createdEventCounter); cache.Put("key1", "value1"); createdSemaphore.WaitOne(); Assert.AreEqual(1, createdEventCounter); cache.removeClientListener(cl); }
/// <summary> /// Instantiates TcpReceiver /// </summary> /// <param name="ipAddress">IP address to monitor for TCP messages</param> /// <param name="port">Network port to monitor for TCP messages</param> /// <param name="evtConsumer">Consumer for events raised by Niawa.MsEventController.EventRaiser</param> public TcpReceiver(string ipAddress, int port, string remoteIpAddress, Niawa.MsEventController.EventConsumer evtConsumer, Niawa.Utilities.UtilsServiceBus utilsBus, string applicationNameDetailed, string parentNodeID) { try { _applicationNameDetailed = applicationNameDetailed; _ipAddress = ipAddress; _remoteIpAddress = remoteIpAddress; _port = port; _portMin = 0; _portMax = 0; lockSection = new System.Threading.Semaphore(1, 1); _description = "TcpReceiver " + _remoteIpAddress + ":" + _port.ToString(); _receiveQueue = new Queue<NiawaNetMessage>(); _evtConsumer = evtConsumer; _utilsBus = utilsBus; //initialize event logging _evtRaiser = new MsEventController.EventRaiser("TcpReceiver", _applicationNameDetailed, _description, utilsBus); //_evtRaiserMsg = new MsEventController.EventRaiser("TcpReceiverMsg", _applicationNameDetailed, _description, utilsBus); if (_evtConsumer != null) _evtRaiser.AddEventConsumer(_evtConsumer); //if (_evtConsumer != null) _evtRaiserMsg.AddEventConsumer(_evtConsumer); //thread status _threadStatus = new Niawa.Threading.ThreadStatus(_description, 300, utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_THREAD_ID).ToString(), parentNodeID, _evtRaiser); //add thread elective properties. _threadStatus.AddElectiveProperty("IpAddress", _ipAddress); _threadStatus.AddElectiveProperty("RemoteIpAddress", _remoteIpAddress); _threadStatus.AddElectiveProperty("Port", _port.ToString()); _threadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_INITIALIZED ; } catch (Exception ex) { logger.Error("[TcpReceiver-M] Error instantiating: " + ex.Message, ex); throw ex; } }
/// <summary> /// Instantiates UdpTransmitter. /// </summary> /// <param name="port">Port to transmit UDP messages on.</param> /// <param name="evtConsumer">Consumer for events raised by Niawa.MsEventController.EventRaiser</param> public UdpTransmitter(int port, Niawa.MsEventController.EventConsumer evtConsumer, Niawa.Utilities.UtilsServiceBus utilsBus, string applicationNameDetailed, string parentNodeID) { try { _applicationNameDetailed = applicationNameDetailed; _port = port; _sendQueue = new Queue<NiawaNetDatagram>(); _sentMessageGuidBuffer = new List<Guid>(); lockSection = new System.Threading.Semaphore(1, 1); lockSentMessageGuidBuffer = new System.Threading.Semaphore(1, 1); _description = "UdpTransmitter " + _port.ToString(); _evtConsumer = evtConsumer; //initialize the endpoints _groupEndpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, _port); //_localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, _port); //initialize serial ID generator id = utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_NET_DATAGRAM); //initialize event logging _evtRaiser = new MsEventController.EventRaiser("UdpTransmitter", _applicationNameDetailed, _description, utilsBus); if (_evtConsumer != null) _evtRaiser.AddEventConsumer(_evtConsumer); _threadStatus = new Niawa.Threading.ThreadStatus(_description, 60, utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_THREAD_ID).ToString(), parentNodeID, _evtRaiser); //thread status _threadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_INITIALIZED; //add thread elective properties. _threadStatus.AddElectiveProperty("Port", _port.ToString()); } catch (Exception ex) { logger.Error("[UdpTransmitter-M] Error while instantiating: " + ex.Message, ex); throw ex; } }
/// <summary> /// Instantiates a new IpcEventWebApiWriter. /// </summary> /// <param name="webApiUrl"></param> /// <param name="utilsBus"></param> public IpcEventWebAPIWriter(string webApiUrl, Niawa.Utilities.UtilsServiceBus utilsBus) { try { _description = "IpcEventWebAPIWriter"; _webApiUrl = webApiUrl; _utilsBus = utilsBus; _messages = new Queue<IpcController.IpcEvent>(); _eventReaders = new SortedList<string, IpcEventReaderThread>(); lockSection = new System.Threading.Semaphore(1, 1); _threadStatus = new Niawa.Threading.ThreadStatus(_description, 60, utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_THREAD_ID).ToString(), string.Empty, null); //thread status _threadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_INITIALIZED; } catch (Exception ex) { logger.Error("[IpcEventWebAPIWriter-M] Error while instantiating: " + ex.Message, ex); } }
/// <summary> /// Instantiates a new WebAPICommandReader. /// </summary> /// <param name="webApiUrl"></param> /// <param name="utilsBus"></param> public WebAPICommandReader(string webApiUrl, int pollIntervalMs, Niawa.Utilities.UtilsServiceBus utilsBus) { try { _description = "WebAPICommandReader"; _webApiUrl = webApiUrl; _pollIntervalMs = pollIntervalMs; if (pollIntervalMs < 1000) { logger.Warn("[WebAPICommandReader-M] Warning: poll interval under minimum, setting to 1000 ms"); _pollIntervalMs = 1000; } if (pollIntervalMs > 60000) { logger.Warn("[WebAPICommandReader-M] Warning: poll interval over maximum, setting to 60000 ms"); _pollIntervalMs = 60000; } lockSection = new System.Threading.Semaphore(1, 1); _utilsBus = utilsBus; _messages = new Queue<NiawaWebMessage>(); _cachedMessages = new SortedList<int, NiawaWebMessage>(); _subscribedCommands = new List<int>(); _threadStatus = new Niawa.Threading.ThreadStatus(_description, 60, utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_THREAD_ID).ToString(), string.Empty, null); //thread status _threadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_INITIALIZED; } catch (Exception ex) { logger.Error("[WebAPICommandReader-M] Error while instantiating: " + ex.Message, ex); } }
public bool Stop() { if (this.synchronizer != null) { this.synchronizer.Close(); this.synchronizer = null; } return true; }
Int32 ReceiveLength = 0; //用于串口接收个数 #endregion Fields #region Constructors public UartProtocol(SerialPort SpSlot) { mSpSlot = SpSlot; mSemaphore = new System.Threading.Semaphore(0, 1); mSpSlot.ReceivedBytesThreshold = 1; }
/// <summary> /// Instantiate TcpSessionManager with specific utility bus, and event consumer passed in by caller /// </summary> /// <param name="ipAddress"></param> /// <param name="portRangeMin"></param> /// <param name="portRangeMax"></param> /// <param name="hostname"></param> /// <param name="applicationName"></param> /// <param name="evtConsumer"></param> /// <param name="utilsBus"></param> public TcpSessionManager(string ipAddress, int portRangeMin, int portRangeMax, string hostname, string applicationName, Niawa.Utilities.UtilsServiceBus utilsBus, Niawa.MsEventController.EventConsumer evtConsumer, string parentNodeID) { try { _description = "TcpSessionManager"; _ipAddress = ipAddress; _handshakePort = 0; _portRangeMin = portRangeMin; _portRangeMax = portRangeMax; _hostname = hostname; _applicationName = applicationName; _tcpSessions = new SortedList<string, TcpSession>(); _utilsBus = utilsBus; _evtConsumer = evtConsumer; //initialize event logging for this object _evtRaiser = new MsEventController.EventRaiser("TcpSessionManager", _applicationName, "TcpSessionManager", _utilsBus); _evtRaiser_HR = new MsEventController.EventRaiser("TcpSessionManager", _applicationName, "TcpSessionManager-HandshakeReceiver", _utilsBus); //_evtRaiserMsg = new MsEventController.EventRaiser("TcpSessionManagerMsg", _applicationName, "TcpSessionManagerMsg", _utilsBus); //add caller's event consumer, if supplied if (_evtConsumer != null) _evtRaiser.AddEventConsumer(_evtConsumer); if (_evtConsumer != null) _evtRaiser_HR.AddEventConsumer(_evtConsumer); //if (_evtConsumer != null) _evtRaiserMsg.AddEventConsumer(_evtConsumer); lockSection = new System.Threading.Semaphore(1, 1); _receiveQueue = new Queue<NiawaNetMessage>(); Utilities.SerialId threadID_HR = utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_THREAD_ID); Utilities.SerialId threadID_SRL = utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_THREAD_ID); _t2_SRL_ThreadStatus = new Niawa.Threading.ThreadStatus("TcpSessionManager", 60, threadID_SRL.ToString(), parentNodeID, _evtRaiser); _t1_HR_ThreadStatus = new Niawa.Threading.ThreadStatus("TcpSessionManager-HandshakeReceiver", 60, threadID_HR.ToString(), threadID_SRL.ToString(), _evtRaiser_HR); //thread status _t1_HR_ThreadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_INITIALIZED; _t2_SRL_ThreadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_INITIALIZED; //add thread elective properties. _t1_HR_ThreadStatus.AddElectiveProperty("IpAddress", _ipAddress); _t1_HR_ThreadStatus.AddElectiveProperty("HandshakePort", _handshakePort.ToString()); _t1_HR_ThreadStatus.AddElectiveProperty("Hostname", _hostname.ToString()); _t2_SRL_ThreadStatus.AddElectiveProperty("IpAddress", _ipAddress); _t2_SRL_ThreadStatus.AddElectiveProperty("HandshakePort", _handshakePort.ToString()); _t2_SRL_ThreadStatus.AddElectiveProperty("Hostname", _hostname.ToString()); _t2_SRL_ThreadStatus.AddElectiveProperty("PortRangeMin", _portRangeMin.ToString()); _t2_SRL_ThreadStatus.AddElectiveProperty("PortRangeMax", _portRangeMax.ToString()); } catch (Exception ex) { logger.Error("[TcpSessionManager-M] Error instantiating: " + ex.Message, ex); throw ex; } }
public bool Surface_Calculation() { //Homogeneous media only... SurfaceSource Ssrc = Src as SurfaceSource; List<Hare.Geometry.Point> R; R = new List<Hare.Geometry.Point>(); foreach (Hare.Geometry.Point p in Receiver) R.Add(p); Random rnd = new Random(); int[][][] tau = new int[R.Count][][]; //Rec;Curve;Sample double[][][] dist = new double[R.Count][][]; //Rec;Curve;Sample int[] RecT = new int[R.Count]; Io = new double[R.Count][][]; Validity = new Boolean[R.Count]; double C_Sound = Room.Sound_speed(0); //int MT = MaxT; List<int> rndList = new List<int>(); for (int i = 0; i < R.Count; i++) { rndList.Add(rnd.Next()); } System.Threading.Semaphore S = new System.Threading.Semaphore(1, 1); //for (int k = 0; k < R.Count; k++) System.Threading.Tasks.Parallel.For(0, R.Count, k => { Random RndGen = new Random(rndList[k]); tau[k] = new int[Ssrc.Srfs.Count][]; dist[k] = new double[Ssrc.Srfs.Count][]; for (int i = 0; i < Ssrc.Srfs.Count; i++) { tau[k][i] = new int[Ssrc.Samples[i].Length]; dist[k][i] = new double[Ssrc.Samples[i].Length]; Time_Pt[k] = double.MaxValue; for (int j = 0; j < Ssrc.Samples[i].Length; j++) { Rhino.Geometry.Point3d p = Ssrc.Samples[i][j]; Vector d = R[k] - Utilities.PachTools.RPttoHPt(Ssrc.Samples[i][j]); dist[k][i][j] = d.Length(); double tdbl = dist[k][i][j] / C_Sound; tau[k][i][j] = (int)Math.Ceiling(tdbl * SampleFreq); if (RecT[k] < tau[k][i][j]) RecT[k] = tau[k][i][j]; if (Time_Pt[k] > tdbl) Time_Pt[k] = tdbl; d.Normalize(); Ray D = new Ray(Utilities.PachTools.RPttoHPt(p), d, 0, RndGen.Next()); double x1 = 0, x2 = 0; List<double> t_in; List<int> code; int x3 = 0; List<Hare.Geometry.Point> x4; if (Room.shoot(D, out x1, out x2, out x3, out x4, out t_in, out code)) { if (t_in[0] >= dist[k][i][j]) Validity[k] = true; ; } else { Validity[k] = true; } } } S.WaitOne(); //foreach (int T in RecT) if (MT < T) MT = T; Special_Status.Instance.progress += 1.0f / R.Count; S.Release(); }); //MaxT = MT; for (int rec_id = 0; rec_id < R.Count; rec_id++) { Io[rec_id] = new double[8][]; for(int oct = 0; oct < 8; oct++) { Io[rec_id][oct] = new double[RecT[rec_id] + 1]; } ////Parallel.For(0, SrcPts.Count, i => for (int i = 0; i < Ssrc.Srfs.Count; i++) { for (int j = 0; j < tau[rec_id][i].Length; j++) { double[] Io_t = new double[8]; //Io_t[0] = Ssrc.DomainPower[i][0] * Math.Pow(10,-.1 * Room.Attenuation(0)[0] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]); //Io_t[1] = Ssrc.DomainPower[i][1] * Math.Pow(10,-.1 * Room.Attenuation(0)[1] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]); //Io_t[2] = Ssrc.DomainPower[i][2] * Math.Pow(10,-.1 * Room.Attenuation(0)[2] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]); //Io_t[3] = Ssrc.DomainPower[i][3] * Math.Pow(10,-.1 * Room.Attenuation(0)[3] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]); //Io_t[4] = Ssrc.DomainPower[i][4] * Math.Pow(10,-.1 * Room.Attenuation(0)[4] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]); //Io_t[5] = Ssrc.DomainPower[i][5] * Math.Pow(10,-.1 * Room.Attenuation(0)[5] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]); //Io_t[6] = Ssrc.DomainPower[i][6] * Math.Pow(10,-.1 * Room.Attenuation(0)[6] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]); //Io_t[7] = Ssrc.DomainPower[i][7] * Math.Pow(10,-.1 * Room.Attenuation(0)[7] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]); Io_t[0] = Math.Pow(10, Ssrc.DomainLevel[i][0] / 10) * 1E-12 * Math.Exp(-0.2302 * Room.Attenuation(0)[0] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]) / Ssrc.Samples[i].Length; Io_t[1] = Math.Pow(10, Ssrc.DomainLevel[i][1] / 10) * 1E-12 * Math.Exp(-0.2302 * Room.Attenuation(0)[1] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]) / Ssrc.Samples[i].Length; Io_t[2] = Math.Pow(10, Ssrc.DomainLevel[i][2] / 10) * 1E-12 * Math.Exp(-0.2302 * Room.Attenuation(0)[2] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]) / Ssrc.Samples[i].Length; Io_t[3] = Math.Pow(10, Ssrc.DomainLevel[i][3] / 10) * 1E-12 * Math.Exp(-0.2302 * Room.Attenuation(0)[3] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]) / Ssrc.Samples[i].Length; Io_t[4] = Math.Pow(10, Ssrc.DomainLevel[i][4] / 10) * 1E-12 * Math.Exp(-0.2302 * Room.Attenuation(0)[4] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]) / Ssrc.Samples[i].Length; Io_t[5] = Math.Pow(10, Ssrc.DomainLevel[i][5] / 10) * 1E-12 * Math.Exp(-0.2302 * Room.Attenuation(0)[5] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]) / Ssrc.Samples[i].Length; Io_t[6] = Math.Pow(10, Ssrc.DomainLevel[i][6] / 10) * 1E-12 * Math.Exp(-0.2302 * Room.Attenuation(0)[6] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]) / Ssrc.Samples[i].Length; Io_t[7] = Math.Pow(10, Ssrc.DomainLevel[i][7] / 10) * 1E-12 * Math.Exp(-0.2302 * Room.Attenuation(0)[7] * dist[rec_id][i][j]) / (4 * Math.PI * dist[rec_id][i][j] * dist[rec_id][i][j]) / Ssrc.Samples[i].Length; Io[rec_id][0][tau[rec_id][i][j]] += Io_t[0]; Io[rec_id][1][tau[rec_id][i][j]] += Io_t[1]; Io[rec_id][2][tau[rec_id][i][j]] += Io_t[2]; Io[rec_id][3][tau[rec_id][i][j]] += Io_t[3]; Io[rec_id][4][tau[rec_id][i][j]] += Io_t[4]; Io[rec_id][5][tau[rec_id][i][j]] += Io_t[5]; Io[rec_id][6][tau[rec_id][i][j]] += Io_t[6]; Io[rec_id][7][tau[rec_id][i][j]] += Io_t[7]; } } } return true; }
private void Solve() { _IsRunning = true; while (!_Stop && !_States.IsEmpty()) { MapState ms = _States.Dequeue(); string key = ms.ToString(); if (_FairnessDict.ContainsKey(key) && !double.IsNaN(_FairnessDict[key])) continue; // State already visited BalanceReport br = BalanceChecker.CheckBalance(_Map, _balanceCheckerSettings, ms); _FairnessDict[key] = br.Unfairness; if (br.Unfairness < _TopResultUnfairness) { _TopResultUnfairness = br.Unfairness; TopResult = ms; } foreach (MapState n in ms.GetNeighbouringStates(_Map, _FixedStarts, _MinimumDistanceBetweenCapitals)) { string k = n.ToString(); if (!_FairnessDict.ContainsKey(k)) { _States.Enqueue(n, br.Unfairness); //100000.0 / br.Unfairness); _FairnessDict[k] = double.NaN; } } if (DateTime.Now - _LastProgressTime > ProgressFrequency) { if(Progress != null) Progress(this, EventArgs.Empty); _LastProgressTime = DateTime.Now; } } if(_StoppedSignal != null) _StoppedSignal.Release(); _StoppedSignal = null; _IsRunning = false; }
/// <summary> /// Private function for instantiating UdpReceiver. /// </summary> /// <param name="port"></param> /// <param name="evtConsumer"></param> /// <param name="utilsBus"></param> /// <param name="applicationNameDetailed"></param> /// <param name="parentNodeID"></param> private void Instantiate(int port , Niawa.MsEventController.EventConsumer evtConsumer , Niawa.Utilities.UtilsServiceBus utilsBus , string applicationNameDetailed , string parentNodeID) { try { _applicationNameDetailed = applicationNameDetailed; _port = port; _receiveQueue = new Queue<NiawaNetDatagram>(); _evtConsumer = evtConsumer; lockSection = new System.Threading.Semaphore(1, 1); _description = "UdpReceiver " + _port.ToString(); //initialize the endpoints /*v2*/ //_recvEndpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); //_localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, _port); /*v3*/ _recvEndpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, _port); //initialize event logging _evtRaiser = new MsEventController.EventRaiser("UdpReceiver", _applicationNameDetailed, _description, utilsBus); if (_evtConsumer != null) _evtRaiser.AddEventConsumer(_evtConsumer); _threadStatus = new Niawa.Threading.ThreadStatus(_description, 300, utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_THREAD_ID).ToString(), parentNodeID, _evtRaiser); //thread status _threadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_INITIALIZED; //add thread elective properties. _threadStatus.AddElectiveProperty("Port", _port.ToString()); } catch (Exception ex) { logger.Error("[UdpReceiver-M] Error while instantiating: " + ex.Message, ex); throw ex; } }
/// <summary> /// Inits this instance. /// </summary> private void Init() { Sema = new System.Threading.Semaphore(0, 100, "Horse"); InstNum = Sema.Release(1); // Initialize unmanged memory to hold the array. int size = Marshal.SizeOf(horsedata[0][0]) * horsedata[0].Length; for (int i = 0; i < horsedata.Length; ++i) { IntPtr pnt = Marshal.AllocHGlobal(size); Marshal.Copy(horsedata[i], 0, pnt, size); Bitmap bmp = new Bitmap(64, 29, 8, PixelFormat.Format1bppIndexed, pnt); ColorPalette cp = bmp.Palette; cp.Entries[0] = ColorTable[InstNum & 3]; cp.Entries[1] = Color.Black; bmp.Palette = cp; bmps[i] = bmp; } timer1.Enabled = true; this.BackColor = ColorTable[InstNum % ColorTable.Length]; IntPtr SysMenu = Win32Api.GetSystemMenu(this.Handle, false); Win32Api.AppendMenu(SysMenu, Win32Api.MenuFlags.MF_SEPARATOR, 0, null); Win32Api.AppendMenu(SysMenu, Win32Api.MenuFlags.MF_STRING, menuCenterID, "&Center"); Win32Api.AppendMenu(SysMenu, Win32Api.MenuFlags.MF_STRING, menuAboutID, "&About..."); }
public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); searching = new System.Threading.Semaphore(1,1); stdOut.DeactivateDebug(); stdOut.SetInterface(StdOutInterfaces.WindowsForm); EDOLLHandler.Start(false); log = new M3SFrameLog(); // // TODO: Add constructor code after the InitializeComponent() call. // }
public static double[] ETCToPTC(double[][] Octave_ETC, double CutOffTime, int sample_frequency_in, int sample_frequency_out, double Rho_C) { int length = 4096; double[] IR = new double[(int)Math.Floor(sample_frequency_out * CutOffTime) + (int)length]; double BW = (double)sample_frequency_out / (double)sample_frequency_in; //Convert to Pressure & Interpolate full resolution IR int ct = 0; System.Threading.Semaphore S = new System.Threading.Semaphore(0, 1); S.Release(1); double[] time = new double[(int)Math.Floor(sample_frequency_out * CutOffTime) + (int)length]; double dt = 1f/(float)sample_frequency_out; for (int i = 0; i < time.Length; i++) { time[i] = i * dt; } int proc = UI.PachydermAc_PlugIn.Instance.ProcessorSpec(); double[][] output = new double[proc][]; double[][] samplep = new double[proc][]; System.Threading.Thread[] T = new System.Threading.Thread[proc]; int[] to = new int[proc]; int[] from = new int[proc]; System.Threading.CountdownEvent CDE = new System.Threading.CountdownEvent(Octave_ETC[0].Length); for (int p = 0; p < proc; p++) { output[p] = new double[length]; samplep[p] = new double[length * 2]; to[p] = p * Octave_ETC[0].Length / proc; from[p] = (p + 1) * Octave_ETC[0].Length / proc; T[p] = new System.Threading.Thread((thread) => { int thr = (int)thread; for (int t = to[thr]; t < from[thr]; t++) { ct++; double[] pr = new double[8]; for (int oct = 0; oct < 8; oct++) pr[oct] = Math.Sqrt(Octave_ETC[oct][t] * Rho_C); double sum = 0; foreach (double d in pr) sum += d; if (sum > 0) { output[thr] = Filter.Signal(pr, sample_frequency_out, 4096, thr); //Audio.Pach_SP.Raised_Cosine_Window(ref output[thr]); for (int k = 0; k < length; k++) { IR[(int)Math.Floor(t * BW) + k] += output[thr][k]; } } CDE.Signal(); } }); T[p].Start(p); } ProgressBox VB = new ProgressBox("Signal Production Progress"); VB.Show(); do { if (CDE.IsSet) { break; } VB.Populate((int)(100 * (1f - ((float)CDE.CurrentCount / (float)IR.Length)))); System.Threading.Thread.Sleep(500); } while (true); //CDE.Wait(); VB.Close(); return IR; }
public Request(Point Start, Point End, Pathfind m_Pathfind) { this.Start = Start; this.End = End; this.m_Pathfind = m_Pathfind; Done = new System.Threading.Semaphore(0, 1); System.Threading.Thread RequestThread = new System.Threading.Thread(Run); RequestThread.Start(); }
static LogHelper() { semaphore = new System.Threading.Semaphore(1, 1); }
public DbConnection(string dbName, string connString, int maxCount, int timeOut, ClientType dbType) { this.m_connString = connString; this.m_semaphore = maxCount; this.m_dbName = dbName; this.m_maxCount = maxCount; this.m_timeOut = timeOut; this.m_dbType = dbType; this.m_connectionInfoList = new ArrayList(); FSemaphore = new System.Threading.Semaphore(maxCount, maxCount); FMutex = new System.Threading.Mutex(); }
public bool Start() { this.configurationService = this.manager.ConfigurationService; this.sipService = this.manager.SipService; this.contactService = this.manager.ContactService; #if !ASYNCHRONOUSLY this.synchronizer = new System.Threading.Semaphore(0, 1); #endif return true; }
/// <summary> /// Adds particle points to this class for display based on the distance traveled from the source. /// </summary> /// <param name="Dist"></param> public void Populate(double Dist, bool Nearest_Neighbor) { Mesh_Vis = false; Section_Vis = false; PC = new PointCloud(); this.Enabled = false; double[] e = new double[PR.Length * PR[0].Count()]; Point3d[] pts = new Point3d[PR.Length * PR[0].Count()]; int[][] voxel = new int[e.Length][]; for (int s = 0; s < PR.Length; s++) { for (int q = 0; q < PR[s].Count(); q++) { double energy; Point3d N, PT; if (!PR[s].RayPt(q, Dist, 4, out energy, out N, out PT)) continue; Vector3d loc = PT - min; int x = (int)System.Math.Floor(loc.X / dx); int y = (int)System.Math.Floor(loc.Y / dy); int z = (int)System.Math.Floor(loc.Z / dz); int id = q + s * PR[s].Count(); ptgrid[x,y,z].Add(id); voxel[id] = new int[3] { x, y, z }; pts[id] = PT; e[id] = energy; } } //foreach(int[] i in voxel) //{ // if (i == null) // { // Rhino.RhinoApp.WriteLine("oops..."); // } //} System.Threading.Semaphore S = new System.Threading.Semaphore(1, 1); if (Nearest_Neighbor) { System.Threading.Tasks.Parallel.For(0, pts.Length, s => //for (int s = 0; s < pts.Length; s++) { if (voxel[s] != null) { double energy = e[s]; foreach (int[] sp in SearchPattern) { int x = voxel[s][0] + sp[0]; int y = voxel[s][1] + sp[1]; int z = voxel[s][2] + sp[2]; if (x < 0 || x > nx - 1 || y < 0 || y > ny - 1 || z < 0 || z > nz - 1) continue; foreach (int t in ptgrid[x, y, z]) { if (s == t) continue; Vector3d pt = pts[s] - pts[t]; double d2 = pt.X * pt.X + pt.Y * pt.Y + pt.Z * pt.Z; if (d2 < 1) { energy += e[t] * (1 - d2); } } } S.WaitOne(); PC.Add(pts[s], P_Color(Utilities.AcousticalMath.SPL_Intensity(energy))); S.Release(); } }); foreach (List<int> p in ptgrid) { p.Clear(); } } else { for (int s = 0; s < pts.Length; s++) { PC.Add(pts[s], P_Color(Utilities.AcousticalMath.SPL_Intensity(e[s]))); } } this.Enabled = true; }