public void AddButton(string text, VoidFunc onClick) { Control buttonControl = new Control(buttonPrefab); ShowResult result = buttonControl.Show(); if (result == ShowResult.FIRST) { buttons.Add(buttonControl); if (listObject) { buttonControl.Instance.transform.SetParent(listObject.transform); } // set button hook ButtonHook buttonHook = buttonControl.Instance.GetComponent <ButtonHook>(); if (buttonHook != null) { buttonHook.onClick = onClick; buttonHook.text = text; } else { Debug.LogWarning("No Button Hook found."); } } }
public ThreadedWorkManager(VoidFunc workProc) { _workProc = workProc; _worker = new Thread(WorkerProcess); _worker.Start(); }
/// <summary> /// Add a new callback function to the worker thread. /// The 'main' delegate will run on a secondary thread, while the 'finished' delegate will run in Update(). /// </summary> static public void CreateConditional(BoolFunc main, VoidFunc finished = null) { if (mInstance == null) { #if UNITY_EDITOR if (!Application.isPlaying) { if (main() && finished != null) { finished(); } return; } #endif GameObject go = new GameObject("Worker Thread"); mInstance = go.AddComponent <WorkerThread>(); } Entry ent; if (mInstance.mUnused.Count != 0) { lock (mInstance.mUnused) { ent = (mInstance.mUnused.size != 0) ? mInstance.mUnused.Pop() : new Entry(); } } else { ent = new Entry(); } ent.conditional = main; ent.finished = finished; lock (mInstance.mNew) mInstance.mNew.Enqueue(ent); }
/// <summary> /// Builds a List of messages, and keeps last one. /// </summary> private void ShowSavedMessages() { if (this.InvokeRequired) { VoidFunc f = new VoidFunc(ShowSavedMessages); this.BeginInvoke(f); } MqttMessage[] AllMsgs = m_mqtt.GetAllSavedMessages(); //TopicComparer sorter = new TopicComparer(); //Array.Sort(AllMsgs, sorter); //DataTable dt = new DataTable("Messages"); //dt.Columns.Add("Topic", typeof(string)); //dt.Columns.Add("Seq", typeof(string)); //dt.Columns.Add("TS", typeof(string)); //dt.Columns.Add("Payload", typeof(string)); m_MessageTable.Rows.Clear(); foreach (MqttMessage m in AllMsgs) { string sseq = string.Format("{0,0}", m.Sequence); string sts = string.Format("{0,0}", m.Timestamp); string data = m.Message; if (data.Length > 1000) { data = data.Substring(0, 1000); } m_MessageTable.Rows.Add(m.Topic, sseq, sts, data); } //dataGridView1.DataSource = m_MessageTable; //textBoxMqttList.Lines = x.ToArray(); }
/// <summary> /// Mediator set setting to all owned setting pages /// </summary> /// <param name="setting">The setting.</param> public void SetSetting(object setting) { if (setting == null) { return; } if (this.InvokeRequired) { VoidFunc <object> functor = this.SetSetting; this.Invoke(functor, setting); } else { if (_settingPagesMapping == null) { throw new Exception("Not initialized"); } foreach (Control ctrl in _settingPagesMapping.Values) { ISettingView settingCtrl = ctrl as ISettingView; if (settingCtrl != null) { settingCtrl.SetSetting(setting); } } } }
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 public static void RegisterBundles(BundleCollection bundles) { BundleTable.EnableOptimizations = false; OrnamentContext.Configuration.SetSeajsCombine(false); bundles.UseCdn = true; var registryParty = new VoidFunc <BundleCollection>[] { GlobalStyle, CodeStyle, Fx, RegistryCtrl, Comp, SeajsModules }; foreach (var item in registryParty) { item.Invoke(bundles); } var manager = new ScriptsFolderManager(); manager.RegisterBundles(bundles); }
/// <summary> /// 以同步的方式自动分配数据到多个线程中区 /// </summary /// <typeparam name="T"></typeparam> /// <param name="threadCount"></param> /// <param name="data"></param> /// <param name="executeFunction"></param> public static void AvgExecute <T>(this T[] data, int threadCount, VoidFunc <T[]> executeFunction) { var thread = new MultiExecute(threadCount); thread.Execute(data, executeFunction); }
public void Create(IProjectDao dao) { var p = new Project(Product) { Name = Name, }; dao.SaveOrUpdate(p); var _roleDao = OrnamentContext.Current.MemberShipFactory().CreateRoleDao(); var addMethod = new VoidFunc <IPerformer[], Role>((performers, role) => { _roleDao.SaveOrUpdate(role); _roleDao.Flush(); foreach (IPerformer performer in performers) { var member = (IMember)performer; member.AddRole(role); } }); addMethod(Testers, p.Tester); addMethod(Developers, p.Developer); addMethod(TesterManager, p.TestManager); addMethod(DeveloperManager, p.DeveloperManager); }
public static void Regist(VoidFunc mvcNormalInit, Type httpErrorControllerType, Assembly webAssembly) { //AddProtableMessageHandler(); Exception nhibernateException = null; mvcNormalInit(); try { NHConfig.Instance.Regist(); //初始化NH配置 } catch (Exception ex) { LogManager.GetLogger(typeof(MvcWebConfig)).Fatal("nhibernate mapping error.", ex); nhibernateException = ex; } NHibernateMvcRegister.Regist(); //修改MVC ModelHandler等配置 ExtenderModelType(); // GlobalConfiguration.Configuration.DependencyResolver = new CastleDependcyResolver(); //新的Attribute,用于JquerUI spinner控件一起用 DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(JqStepAttribute), typeof(StepAttributeAdapter)); //把ControllerFactory和castle联系起来 ChangeControllerFacotry(httpErrorControllerType, webAssembly); //Web MemberShip的加密方法 User.ValidateUserPolicy = new WebValidateUserPolicy(Membership.Provider); //加入Assembly合并模块是,插入到第二为,因为第一位是ReferenceFactory SeajsModuleFactory.Instance.Add(new CombineModuleAsssemblyFactory(), 1); SeajsModuleBundleMessageHandle.HandlAllBundle(); }
/// <summary> /// This wrapping a foreach in C#. /// </summary> /// <param name="list"> Target list. </param> /// <param name="func"> Apply function. </param> public static void ForEach(List <T> list, VoidFunc func) { foreach (T t in list) { func(t); } }
static void Main() { int y = 0; int r; // // The following tests body-style lambda // increment = (int x) => { return(x + 1); }; r = increment(4); Console.WriteLine("Should be 5={0}", r); // // This tests the body of a lambda being an expression // func = (int x) => x + 1; r = func(10); Console.WriteLine("Should be 11={0}", r); // // The following tests that the body is a statement // nothing = (int x) => { y = x; }; nothing(10); Console.WriteLine("Should be 10={0}", y); nothing = (int x) => { new X(x); }; nothing(314); //if (instantiated_value != 314) // return 4; Console.WriteLine("All tests pass"); Console.WriteLine("<%END%>"); }
public static void RunFunctionToPhoton(PhotonView photonView, VoidFunc myFunc, bool isRpcAll = false) { if (isRpcAll) { photonView.RPC(myFunc.Method.Name, RpcTarget.All); //Debug.Log("photon ID: " + photonView.ViewID); //Debug.Log("What is this: " + myFunc.Method.Name); }// if: 리모트 콜백을 해야 하는 경우 else { if (PhotonNetwork.IsConnected) { if (photonView.IsMine) { myFunc(); } else { return; } } else { MyMessages(MessageType.Network_connectable, "Photon network connect", false); } }// else: 스스로 콜백을 해야 하는 경우 }
public void Execute <T>(T[] data, VoidFunc <T[]> executeFunc, VoidFunc threadComplete, VoidFunc callback) { if (data == null) { throw new ArgumentNullException("data"); } if (data.Length == 0) { return; } if (executeFunc == null) { throw new ArgumentNullException("executeFunc"); } if (threadComplete == null) { throw new ArgumentNullException("threadComplete"); } var handler = new VoidFunc <T[], VoidFunc <T[]>, VoidFunc>(ActualExecute); handler.BeginInvoke(data, executeFunc, threadComplete, a => { if (callback != null) { callback(); } }, null); }
/// <summary> /// 处理请求 /// </summary> /// <param name="url"></param> /// <param name="param"></param> /// <param name="cookies"></param> /// <param name="method"></param> /// <param name="timeout_second"></param> /// <param name="handler"></param> public static void HttpRequestHandler( string url, Dictionary <string, string> param, List <Cookie> cookies, RequestMethodEnum method, int timeout_second, VoidFunc <HttpWebResponse, HttpStatusCode> handler) { HttpWebRequest req = null; HttpWebResponse res = null; try { //连接到目标网页 req = (HttpWebRequest)WebRequest.Create(url); req.Timeout = timeout_second * 1000;//10s请求超时 req.Method = GetMethod(method); req.ContentType = "application/x-www-form-urlencoded"; //添加cookie if (ValidateHelper.IsPlumpList(cookies)) { req.CookieContainer = new CookieContainer(); foreach (var c in cookies) { req.CookieContainer.Add(c); } } //如果是post并且有参数 if (method == RequestMethodEnum.POST && ValidateHelper.IsPlumpDict(param)) { param = param.NotNull(); var post_data = param.ToUrlParam(); var data = Encoding.UTF8.GetBytes(post_data); using (var stream = req.GetRequestStream()) { stream.Write(data, 0, data.Length); } } res = (HttpWebResponse)req.GetResponse(); handler.Invoke(res, res.StatusCode); } catch (Exception e) { e.AddErrorLog(); throw e; } finally { try { req?.Abort(); } catch (Exception e) { e.AddLog(typeof(HttpClientHelper)); } res?.Dispose(); } }
/// <summary> /// execute and callback /// </summary> /// <param name="execute"></param> /// <param name="callback"></param> public static void Execute(VoidFunc execute, VoidFunc callback) { ThreadPool.QueueUserWorkItem(s => { execute(); callback(); }); }
/// <summary> /// Callback when connection status has changed. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ConnectionStatusChanged(object sender, EventArgs e) { if (m_dead) { return; } VoidFunc func = new VoidFunc(CheckStatus); }
/* * UnitCommand() * * constructor, specifies the target tile and callback * * @param Unit u - the unit that made this command * @param VoidFunc scb - the callback to use when finished * @param VoidFunc fcb - the callback to use when failed * @param Tiles st - the first tile selected * @param Tiles et - the last tile selected */ public UnitCommand(Unit u, VoidFunc scb, VoidFunc fcb, Tiles st, Tiles et) { unit = u; successCallback = scb; failedCallback = scb; startTile = st; endTile = et; }
public ParseRule(string regex, VoidFunc <Match> parseAction) { ArgumentValidator.ThrowIfNullOrEmpty(regex, "regex"); ArgumentValidator.ThrowIfNull(parseAction, "parseAction"); this.m_regex = new Regex(regex, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.ExplicitCapture); this.m_parseAction = parseAction; }
public ParseRule(string regex, VoidFunc<Match> parseAction) { ArgumentValidator.ThrowIfNullOrEmpty(regex, "regex"); ArgumentValidator.ThrowIfNull(parseAction, "parseAction"); this.m_regex = new Regex(regex, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.ExplicitCapture); this.m_parseAction = parseAction; }
/* * DeathCommand() * * constructor, specifies the target tile and callback * * @param Unit u - the unit that made this command * @param VoidFunc scb - the callback to use when finished * @param VoidFunc fcb - the callback to use when failed * @param Tiles st - the first tile selected * @param Tiles et - the last tile selected */ public DeathCommand(Unit u, VoidFunc scb, VoidFunc fcb, Tiles st, Tiles et) : base(u, scb, fcb, st, et) { if (unit.ArtLink != null) { unit.ArtLink.SetTrigger("Death"); } //disconnect the unit from the grid startTile.unit = null; }
/// <summary> /// Performs the specified action on each element in a collection /// </summary> public static IEnumerable <T> ForEach <T>(IEnumerable <T> colletion, VoidFunc <T> action) { foreach (T t in colletion) { action(t); } return(colletion); }
private static void DelayHook(Object myObject, EventArgs myEventArgs) { Timer timer = myObject as Timer; VoidFunc func = timer.Tag as VoidFunc; timer.Stop(); func(); }
internal HighlightedOutputWriter(ICodeFormatter codeFormatter, bool asynchrounous) { this.m_windows = new Queue<InputWindow>(2); this.m_modesQueue = new Queue<List<KeyValuePair<int, HighlightMode>>>(2); this.m_codeFormatter = codeFormatter; this.m_posCurrent = 0; this.m_drainModesQueue = this.DrainModesQueue; this.m_asynchrounous = asynchrounous; }
internal HighlightedOutputWriter(ICodeFormatter codeFormatter, bool asynchrounous) { this.m_windows = new Queue <InputWindow>(2); this.m_modesQueue = new Queue <List <KeyValuePair <int, HighlightMode> > >(2); this.m_codeFormatter = codeFormatter; this.m_posCurrent = 0; this.m_drainModesQueue = this.DrainModesQueue; this.m_asynchrounous = asynchrounous; }
private double Trampoline(VoidFunc function) { double success = -1; while (success == -1) { success = function(); } return(success); }
public static void Do(VoidFunc func, int msDelay) { Timer delayTimer = new Timer(); delayTimer.Tag = func; delayTimer.Tick += new EventHandler(DelayHook); delayTimer.Interval = msDelay; delayTimer.Start(); }
IEnumerator DelayVoidFunction(int frames, VoidFunc func) { int numSkipped = 0; while (numSkipped++ < frames) { yield return(null); } func(); }
public void Invoke(VoidFunc function, OperationType requestedOperation = OperationType.Write) { Lock(requestedOperation); try { function(); } finally { Unlock(requestedOperation); } }
public void Invoke <T1, T2>(VoidFunc <T1, T2> function, T1 arg1, T2 arg2, OperationType requestedOperation = OperationType.Write) { Lock(requestedOperation); try { function(arg1, arg2); } finally { Unlock(requestedOperation); } }
/// <summary> /// fade from black to clear /// </summary> private void _fadeBlack2Clear() { m_fadeTimer += m_fadeSpeed * Time.deltaTime; // Lerp the colour of the texture between itself and transparent. Color color = Color.Lerp(m_startImage.color, Color.clear, m_fadeTimer * m_fadeTimer); m_fade_black_image.color = color; if (m_fadeTimer > 1) // { m_fadeTimer = 0.0f; fadeFunc = null; } }
public static void CheckAuthentication(VoidFunc init, VoidFunc close) { SettingsManager.ForceLogin = true; if (TpAuthenticationManager.Instance.IsAuthenticatedWithLoginForm) { init(); } else { close(); } }
public static void SendHttpRequest( string url, Dictionary <string, string> param, Dictionary <string, FileModel> files, List <Cookie> cookies, RequestMethodEnum method, int timeout_second, VoidFunc <HttpResponseMessage> handler) { var t = SendHttpRequestAsync(url, param, files, cookies, method, timeout_second, handler); AsyncHelper.RunSync(() => t); }
/* * SpreadAttackCommand() * * constructor, specifies the target tile and callbacks * * @param Unit u - the unit that made this command * @param VoidFunc scb - the callback to use when finished * @param VoidFunc fcb - the callback to use when failed * @param Tiles st - the first tile selected * @param Tiles et - the last tile selected */ public SpreadAttackCommand(Unit u, VoidFunc scb, VoidFunc fcb, Tiles st, Tiles et) : base(u, scb, fcb, st, et) { //face the target unit.GetComponentInChildren <FaceMovement>().directionOverride = (et.pos - st.pos).normalized; //find the map component map = GameObject.FindObjectOfType <Map>(); // Attacking the enemy unit Anim if (unit.ArtLink != null) { unit.ArtLink.SetTrigger("Attack"); } }
public SlidingWindowReader(TextReader reader) { ArgumentValidator.ThrowIfNull(reader, "reader"); this.m_buffer = new char[WindowSize + 250]; this.m_readBlockDelegate = reader.ReadBlock; this.m_queueMoreWindows = this.QueueMoreWindows; this.m_lineEnds = new List<int>((WindowSize + CntSafetyMargin)/40); this.m_inputWindowQueue = new Queue<InputWindow>(4); this.m_windowIsReady = new ManualResetEvent(false); this.m_windowBuilder = new StringBuilder(4 + CntSafetyMargin + 256); this.m_readBlockResult = this.m_readBlockDelegate.BeginInvoke(this.m_buffer, 0, WindowSize, null, null); this.m_queueMoreWindowsResult = this.m_queueMoreWindows.BeginInvoke(null, null); this.AdvanceWindow(); }
static int Main () { int y = 0; int r; // // The following tests body-style lambda // increment = (int x) => { return x + 1; }; r = increment (4); Console.WriteLine ("Should be 5={0}", r); if (r != 5) return 1; // // This tests the body of a lambda being an expression // func = (int x) => x + 1; r = func (10); Console.WriteLine ("Should be 11={0}", r); if (r != 11) return 2; // // The following tests that the body is a statement // nothing = (int x) => { y = x; }; nothing (10); Console.WriteLine ("Should be 10={0}", y); if (y != 10) return 3; nothing = (int x) => { new X (x); }; nothing (314); if (instantiated_value != 314) return 4; Console.WriteLine ("All tests pass"); return 0; }
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 public static void RegisterBundles(BundleCollection bundles) { BundleTable.EnableOptimizations = false; OrnamentContext.Configuration.SetSeajsCombine(false); bundles.UseCdn = true; var registryParty = new VoidFunc<BundleCollection>[] { GlobalStyle, CodeStyle, Fx, RegistryCtrl, Comp, SeajsModules }; foreach (var item in registryParty) { item.Invoke(bundles); } var manager = new ScriptsFolderManager(); manager.RegisterBundles(bundles); }
public static void InAMoment(VoidFunc func) { Do(func, 1); }
public void Create(IProjectDao dao) { var p = new Project(Product) { Name = Name, }; dao.SaveOrUpdate(p); var _roleDao = OrnamentContext.Current.MemberShipFactory().CreateRoleDao(); var addMethod = new VoidFunc<IPerformer[], Role>((performers, role) => { _roleDao.SaveOrUpdate(role); _roleDao.Flush(); foreach (IPerformer performer in performers) { var member = (IMember)performer; member.AddRole(role); } }); addMethod(Testers, p.Tester); addMethod(Developers, p.Developer); addMethod(TesterManager, p.TestManager); addMethod(DeveloperManager, p.DeveloperManager); }
private void AddParsingRule(string regex, VoidFunc<Match> parseAction) { bool substituted; do { substituted = false; foreach (string substitution in m_regexSubstitutions.Keys) { string newRegex = regex.Replace(substitution, m_regexSubstitutions[substitution]); if (newRegex != regex) { substituted = true; } regex = newRegex; } } while (substituted); ParseRule rule = new ParseRule(regex, parseAction); this.m_parseRules.Add(rule); }
public static extern int setOSCEvents(IntNPtrPassFunc RoundStart, IntFunc Countdown, IntFunc Holding, IntFunc HoldFail, VoidFunc Timeout, ThreeIntFunc ShapeCompleted, TwoIntFunc ShapeStatus, PlayerStatusFunc PlayerStatus);
static void Main(string[] args) { SetUpOSCPort(); logger = new Logger("./log/log.txt"); AllocFunc allocGlobalFunc = new AllocFunc(Program.allocGlobal); TweetFunc TweetPictureDel = new TweetFunc(Program.TweetPicture); DontThrowOutMaDelegates.Add(TweetPictureDel); PtrPassFunc FullPictureDel = new PtrPassFunc(Program.SaveWholePicture); DontThrowOutMaDelegates.Add(FullPictureDel); PtrPassFunc SkeletonLogDel = new PtrPassFunc(Program.SkeletonLog); DontThrowOutMaDelegates.Add(SkeletonLogDel); int ret = setTweetback(allocGlobalFunc, TweetPictureDel, FullPictureDel,SkeletonLogDel); IntNPtrPassFunc RoundStartDel = new IntNPtrPassFunc(Program.RoundStart); DontThrowOutMaDelegates.Add(RoundStartDel); IntFunc CountdownDel = new IntFunc(Program.Countdown); DontThrowOutMaDelegates.Add(CountdownDel); IntFunc HoldingDel = new IntFunc(Program.Holding); DontThrowOutMaDelegates.Add(HoldingDel); IntFunc HoldFailDel = new IntFunc(Program.HoldingFail); DontThrowOutMaDelegates.Add(HoldFailDel); VoidFunc TimeoutDel = new VoidFunc(Program.Timeout); DontThrowOutMaDelegates.Add(TimeoutDel); ThreeIntFunc ShapeCompletedDel = new ThreeIntFunc(Program.ShapeCompleted); DontThrowOutMaDelegates.Add(ShapeCompletedDel); TwoIntFunc ShapeStatusDel = new TwoIntFunc(Program.ShapeStatus); DontThrowOutMaDelegates.Add(ShapeStatusDel); PlayerStatusFunc PlayerStatusDel = new PlayerStatusFunc(Program.PlayerStatus); DontThrowOutMaDelegates.Add(PlayerStatusDel); ret = setOSCEvents(RoundStartDel, CountdownDel, HoldingDel, HoldFailDel, TimeoutDel, ShapeCompletedDel, ShapeStatusDel, PlayerStatusDel); GameStart(); Action KinectLoop = new Action(openKinectWindow); KinectLoop.BeginInvoke(null, null); bool run = true; //Console.WriteLine("Type -1 and press ENTER to start game."); while (run) { string input = Console.ReadLine(); try { int number = Convert.ToInt32(input); numericCommand(number); } catch { //string commands. switch (input) { case "s": GameID++; startGame(GameID,GameLength); Console.WriteLine("Starting Game " + GameID); break; case "e": endGame(); break; } } input = ""; //yes, this is an infinite loop. Behold! } }
public static void CheckAuthentication(VoidFunc close) { CheckAuthentication(() => { }, close); }