private void HandleClient(TcpClient client) { byte[] buffer = RecieveData(client); var request = HttpRequest.Parse(buffer); InvokeAll(RequestRecieved.GetInvocationList(), request, client); }
private void Transform <T>(T[] values, Func <T, T> transformer) where T : struct { if (TransformedXs == null) { TransformedXs = new IntegerCollection(); } else { TransformedXs.Clear(); } if (AnotherTransformedXs == null) { AnotherTransformedXs = new IntegerCollection(); } else { AnotherTransformedXs.Clear(); } int[][] temp = new int[transformer.GetInvocationList().Length][]; for (int i = 0; i < transformer.GetInvocationList().Length; ++i) { temp[i] = new int[values.Length]; Parallel.For(0, values.Length, j => { var tempDelegate = transformer.GetInvocationList()[i]; temp[i][j] = (int)tempDelegate.DynamicInvoke(j); }); } for (int i = 0; i < transformer.GetInvocationList().Length; ++i) { if (i == 0) { for (int j = 0; j < values.Length; ++j) { TransformedXs.Add(new SoleParameterInteger { X = temp[i][j] }); } } else if (i == 1) { for (int j = 0; j < values.Length; ++j) { AnotherTransformedXs.Add(new SoleParameterInteger { X = temp[i][j] }); } } } }
public void Calc() { Computer computer = new Computer(); int sum = 0; Func <int> func = null; func += computer.Get; func += computer.Post; func += computer.Delete; for (int i = func.GetInvocationList().Length - 1; i >= 0; i--) { Delegate @delegate = func.GetInvocationList()[i]; sum += (int)@delegate.DynamicInvoke(); } }
public static async Task InvokeAndWaitAsync <T>(this Func <T, Task> @event, T arg) { foreach (var func in @event?.GetInvocationList()?.Cast <Func <T, Task> >() ?? Enumerable.Empty <Func <T, Task> >()) { await func(arg); } }
static void Main(string[] args) { Func <string> addWords = new Func <string>(GetWord1); addWords += GetWord2; addWords += GetWord3; string sentence = ""; //way 1 - Begin And End Invoke. //foreach (Func<string> word in addWords.GetInvocationList()) //{ // IAsyncResult ar = word.BeginInvoke(null,null); // sentence += word.EndInvoke(ar); //} //Console.WriteLine(PrintTheSentence(sentence)); //Way 2 - Dynamic Invoke. foreach (Delegate del in addWords.GetInvocationList()) { sentence += (string)del.DynamicInvoke(); } Console.WriteLine(PrintTheSentence(sentence)); Console.ReadLine(); }
/// <summary> /// Verify password, if OK write to repository. /// </summary> /// <param name="conditions">conditions for check password</param> /// <param name="password">password for check</param> /// <returns>Tuple whick contains if password valid and information message.</returns> public Tuple <bool, string> VerifyPassword(Func <string, Tuple <bool, string> > conditions, string password) { if (conditions == null) { throw new ArgumentNullException(nameof(conditions)); } if (password == null) { throw new ArgumentNullException(nameof(password)); } foreach (Delegate condition in conditions.GetInvocationList()) { Tuple <bool, string> tuple = (Tuple <bool, string>)condition.DynamicInvoke(password); if (!tuple.Item1) { return(tuple); } } _repository.Create(password); return(Tuple.Create(true, "Password is Ok. User was created")); }
static void Main(string[] args) { Func <string> func = new Func <string>(() => { return("Asynchronous "); }); func += () => { return("Programming "); }; func += () => { return("Model"); }; string str = ""; List <Task <string> > strList = new List <Task <string> >(); foreach (Delegate del in func.GetInvocationList()) { strList.Add(Task.Run <string>(() => { return((string)del.DynamicInvoke()); })); } Thread.Sleep(500); Task.WaitAll(strList.ToArray()); foreach (Task <string> t in strList) { str += t.Result; } Console.WriteLine(str); }
static void Main(string[] args) { DelegatePrintString delegatePrintString = null; delegatePrintString += new DelegatePrintString(MethodPrintStringLower); delegatePrintString += new DelegatePrintString(MethodPrintStringUpper); delegatePrintString("Output"); Console.WriteLine(); Console.WriteLine(); Func <int> func = delegate { Console.WriteLine("first part"); return(5); }; func += delegate { Console.WriteLine("second part"); return(7); }; int result = func(); Console.WriteLine(result); Console.WriteLine(); Console.WriteLine(); foreach (Func <int> part in func.GetInvocationList()) { result = part(); Console.WriteLine(result); } Console.ReadKey(); }
public static async Task InvokeSequentially(this Func <Task> func) { foreach (var f in func.GetInvocationList().Cast <Func <Task> >()) { await f.Invoke(); } }
static IEnumerable <T> GetAllReturns <T>(Func <T> d) { foreach (Func <T> del in d.GetInvocationList()) { yield return(del()); } }
GetAllReturnValues <Targ>(Func <Targ> d) { foreach (MeDelegate <Targ> del in d.GetInvocationList()) { yield return(del()); } }
protected async Task OnUserRegistered(User user, string code, IUrlHelper url, HttpRequest http) { // if(userRegistered != null) // userRegistered(this, new EmailArgs() { // Email = email, // Id = id, // Code = code, // Url = url, // Http = http // }); Func <object, EmailArgs, Task> handler = Registered; if (handler == null) { return; } Delegate[] invocationList = handler.GetInvocationList(); Task[] handlerTasks = new Task[invocationList.Length]; for (int i = 0; i < invocationList.Length; i++) { handlerTasks[i] = ((Func <object, EmailArgs, Task>)invocationList[i])(this, new EmailArgs() { user = user, Code = code, Url = url, Http = http }); } await Task.WhenAll(handlerTasks); }
static void FunctionSample() { Func <string> function1 = () => "Hello Function1!"; function1 += () => { return("Hello Function 2!"); }; function1 += MessageFunction; Console.Write(function1.Invoke()); foreach (var item in function1.GetInvocationList()) { Console.WriteLine(item.DynamicInvoke()); } Func <int, int, string> function2 = (int a, int b) => $"{a + b}"; function2 += (a, b) => $"{a}{b}"; function2 += MessageFunction1; foreach (var item in function2.GetInvocationList()) { Console.WriteLine((string)item.DynamicInvoke(new object[] { 1, 2 })); } }
public static void Demo() { // delegate = type safe function pointer, immutable // expression lambda - (input-params) => expression MyDelegate1 productIsEven = (x, y) => x * y % 2 == 0; Console.WriteLine(productIsEven(3, 4)); Console.WriteLine(productIsEven(3, 5)); // statement lambda - (input-params) => {statement; } MyDelegate2 greetings = n => { Console.WriteLine("Hello " + n); }; greetings("Guido"); greetings.Invoke("Raymond"); // multicast delegate greetings += new MyDelegate2(Hiya); greetings("Alex"); // multicast with non-void return type Func <int> func = delegate { return(1); }; func += delegate { return(2); }; foreach (Func <int> run in func.GetInvocationList()) // can't use var? { Console.WriteLine(run()); } // generic delegate Func <int, int, bool> productDivByThree = (x, y) => x * y % 3 == 0; Console.WriteLine(productDivByThree(4, 6)); }
public string GetDelegateText(UnityEventFloat ue, Func <float, bool> a) { StringBuilder text = new StringBuilder(); if (ue != null) { for (int i = 0; i < ue.GetPersistentEventCount(); ++i) { if (text.Length > 0) { text.Append("\n"); } UnityEngine.Object obj = ue.GetPersistentTarget(i); string t = obj != null ? obj.name : "<???>"; text.Append(t).Append(".").Append(KBind.EventSet.FilterMethodName(ue.GetPersistentMethodName(i))); } } if (a != null) { Delegate[] delegates = a.GetInvocationList(); for (int i = 0; i < delegates.Length; ++i) { if (text.Length > 0) { text.Append("\n"); } text.Append(delegates[i].Target).Append(".").Append(delegates[i].Method.Name); } } return(text.ToString()); }
IEnumerable <TArg> GetAllReturnValues <TArg>(Func <TArg> d) { foreach (Func <TArg> del in d.GetInvocationList()) { yield return(del()); } }
private static void MulticastDelegateExample() { Calculation += (n1, n2) => n1 + n2; Calculation += (n1, n2) => { throw new InvalidOperationException("Invalid operation"); return(10); }; Calculation += (n1, n2) => n1 - n2; Calculation += (n1, n2) => n1 * n2; Calculation += (n1, n2) => n1 / n2; List <Exception> listException = new List <Exception>(); Parallel.ForEach(Calculation.GetInvocationList(), d => { try { double result = (double)d.DynamicInvoke(10, 10); Console.WriteLine(result); } catch (Exception ex) { listException.Add(ex); } }); }
public static async Task RunSequential <T1>(this Func <T1, Task> del, T1 param1) { foreach (var d in del.GetInvocationList().OfType <Func <T1, Task> >()) { await d(param1); } }
public static bool Execute(this Func <bool> _func, FuncMode _mode = FuncMode.Any, bool _onNull = false) { if (_func == null) { return(_onNull); } bool result = false; Delegate[] list = _func.GetInvocationList(); switch (_mode) { case FuncMode.Any: result = false; for (int i = 0; i < list.Length; i++) { result |= (bool)list[i].DynamicInvoke(); } break; case FuncMode.All: result = true; for (int i = 0; i < list.Length; i++) { result &= (bool)list[i].DynamicInvoke(); } break; } return(result); }
public static async Task InvokeAsync(this Func <Task> @event) { foreach (Func <Task> handler in @event.GetInvocationList()) { await handler.Invoke(); } }
static IEnumerable <TArgs> InvokeFuncChain <TArgs>(Func <TArgs> genDel) { foreach (Func <TArgs> del in genDel.GetInvocationList()) { yield return(del()); } }
public static async Task InvokeAsync <T1, T2, T3>(this Func <T1, T2, T3, Task> @event, T1 arg1, T2 arg2, T3 arg3) { foreach (Func <T1, T2, T3, Task> handler in @event.GetInvocationList()) { await handler.Invoke(arg1, arg2, arg3); } }
/// <summary> /// 登録されているいずれかのデリゲートが true を返す場合 true を返します /// </summary> public static bool Any(this Func <bool> self) { return(self .GetInvocationList() .Any(c => ( bool )c.DynamicInvoke()) ); }
/// <summary> /// 登録されているいずれかのデリゲートが true を返す場合 true を返します /// </summary> public static bool Any <T>(this Func <T, bool> self, T arg) { return(self .GetInvocationList() .Any(c => ( bool )c.DynamicInvoke(arg)) ); }
/// <summary> /// 登録されているいずれかのデリゲートが true を返す場合 true を返します /// </summary> public static bool Any <T1, T2>(this Func <T1, T2, bool> self, T1 arg1, T2 arg2) { return(self .GetInvocationList() .Any(c => ( bool )c.DynamicInvoke(arg1, arg2)) ); }
/// <summary> /// 登録されているすべてのデリゲートが true を返す場合 true を返します /// </summary> public static bool All <T1, T2, T3>(this Func <T1, T2, T3, bool> self, T1 arg1, T2 arg2, T3 arg3) { return(self .GetInvocationList() .All(c => ( bool )c.DynamicInvoke(arg1, arg2, arg3)) ); }
internal bool IsAnagram(string a, string b, Func <string, string> formatter) { /* * Multicast delegates are mostly known for their use in events. Events don't return anything. * Since my delegate returns a string I have to iterate through the invocation list in order * to capture each return value. This really isn't the cleanest because IsAnagram basically * needed to know that it had to approach the delegate in this manner. * If this was production code I'd come up with a cleaner solution so this method didn't need * any knowledge of how it's expecting formatter to be a multicast delegate. */ foreach (Func <string, string> function in formatter.GetInvocationList()) { a = function(a); b = function(b); } if (a.Length != b.Length) { return(false); } /* * This is the LINQ solution. Why go with this solution versus using a dictionary and making * sure char arrays are only iterated through once to do the checks? Because I'm not putting * an arbitrary constraint on this solution. Iterating through the one string to create a * dictionary and iterating through the second to check if the key exists in the dictionary is * an option. This code is quite a bit simpler, in my opinion it's more readable, and it doesn't * prematurely try to optimize code that may not need to be optimized. */ return(a.ToCharArray().Except(b).Count() == 0); }
protected override Task OnFileReciveBegining(RecieveOfFileTransferRequestEventArgs args) { Func <object, RecieveOfFileTransferRequestEventArgs, Task> handlerEvent = RecieveOfFileTransferRequestEvent; if (handlerEvent == null) { return(Task.FromResult(false)); } try { Delegate[] invocationList = handlerEvent.GetInvocationList(); var handlerTasks = new Task[invocationList.Length]; for (int i = 0; i < invocationList.Length; i++) { handlerTasks[i] = ((Func <object, RecieveOfFileTransferRequestEventArgs, Task>)invocationList[i])(this, args); } return(Task.WhenAll(handlerTasks)); } catch (Exception ex) { args.TryAllowContinueRegistration(false, null); return(Task.CompletedTask); } }
private void EZGUIMouseTouchPtrListener(POINTER_INFO ptr) { if (mDelegate == null || mDelegate.GetInvocationList().Length == 0) { Dispose(); mInstance = null; return; } foreach (Func <Rect> d in mDelegate.GetInvocationList()) { if (d.Invoke().Contains(new Vector2(ptr.devicePos.x, Screen.height - ptr.devicePos.y))) { mUsedPointers[0] = true; } } }
public Tuple <bool, string> VerifyPassword(string password, IRepository repository, Func <string, Tuple <bool, string> > verifier) { VerifyInput(password, repository, verifier); if (string.Equals(password, string.Empty, StringComparison.Ordinal)) { return(Tuple.Create(false, $"{nameof(password)} is empty ")); } var verifications = verifier.GetInvocationList(); foreach (var verification in verifications) { var verificationMethod = (Func <string, Tuple <bool, string> >)verification; var result = verificationMethod.Invoke(password); if (!result.Item1) { return(result); } } repository.Create(password); return(Tuple.Create(true, "Password is Ok. User was created")); }
public static bool ProcessSingleMessage( CurrentMessageInformation currentMessageInformation, Func<CurrentMessageInformation, bool> messageRecieved) { if (messageRecieved == null) return false; foreach (Func<CurrentMessageInformation, bool> func in messageRecieved.GetInvocationList()) { if (func(currentMessageInformation)) { return true; } } return false; }
/// <summary> /// Check each of the booleans in a BoolAction. If any of the returns are false, /// return false. If none of them are false, we can return true. /// </summary> /// <param name="actions">Event storage of methods.</param> private bool DoesBoolExist(Func<GameObject, bool> actions, GameObject g) { foreach(Func<GameObject, bool> bAction in actions.GetInvocationList()) { //If the return value of the action is ever false, return value must be false if (bAction(g) == false) { return false; } } return true; }