static void main(string[] args) { Console.WriteLine("***** Simple Delegate Example*****\n"); // instantiate an instance of "simpleMathClass" see above SimpleMath m = new SimpleMath(); // so now lets add the add method of the instance of 'simpleMath' to it. // 'BinaryOp is a delegates that takes 2 ints as parameters and returns an int as a result. BinaryOp b = new BinaryOp(m.Add); //invoke Add() method directly using delegate object Console.WriteLine("Direct invocation... 10+10 is {0}", b(10, 10)); Console.ReadLine(); //invoke Add() method indirectly using delegate object Console.WriteLine("Indirect invocation,.... 10 + 10 is {0}", b.Invoke(10, 10)); Console.ReadLine(); // Change the target method on the fly b = new BinaryOp(m.Substract); Console.WriteLine("Replace add with subtract"); Console.ReadLine(); //invoke the substract method by direactly invoking that delegate Console.WriteLine("Direct invocation.... 15 - 5 is {0}", b(15, 5)); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("***** Async Delegate Invocation *****"); Console.WriteLine("Main() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); IAsyncResult iftAR = b.BeginInvoke(10, 10, new AsyncCallback(AddComplete), "Main() thanks you for adding these numbers."); // using the member method or property of IAsyncResult // involve in Async process. //while (!iftAR.IsCompleted) //{ // Console.WriteLine("Doing more work in Main()"); // Thread.Sleep(1000); //} //while (!iftAR.AsyncWaitHandle.WaitOne(1000, true)) //{ // Console.WriteLine("Doing more work in Main()"); //} while (!isDone) { Thread.Sleep(1500); Console.WriteLine("Woring more work in Main()"); } // 让第二个线程通知访问线程,当第二个线程的工作完成时。 // 向BeginInvoke中传入AsyncCallback delegate,在BeginInvoke的异步调用结束时, // AsyncCallback委托会访问一个特殊的方法。 // AsyncCallback委托的原型: public delegate void AsyncCallback(IAsyncResult ar); //int answer = b.EndInvoke(iftAR); //Console.WriteLine("10 + 10 is {0}", answer); Console.WriteLine("Async work is complete!!"); Console.ReadLine(); }
static void Main(string[] args) { BinaryOp opCode = new BinaryOp(Add); Console.WriteLine("Threading!"); Thread t = System.Threading.Thread.CurrentThread; Console.WriteLine(t.IsAlive); AppDomain ad = Thread.GetDomain(); Console.WriteLine(ad.FriendlyName); System.Runtime.Remoting.Contexts.Context ctx = Thread.CurrentContext; Console.WriteLine("\nMain() thread id: {0}", Thread.CurrentThread.ManagedThreadId); //Console.WriteLine("waits till Add completes, delegate sum: {0}", opCode.Invoke(10, 30)); //IAsyncResult iAsync = opCode.BeginInvoke(10, 50, null, null); //the called thread informs the primary thread that it hascompleted IAsyncResult iAsync = opCode.BeginInvoke(10, 50, new AsyncCallback(AddComplete), "author: naynish c"); Console.WriteLine("Add called async"); //keeps on asking if the call is complete Console.WriteLine("Check if Add is complete {0}", iAsync.IsCompleted); //waits for 200 milliseconds and asks if the call is complete iAsync.AsyncWaitHandle.WaitOne(200); Console.WriteLine("Check if Add is complete {0}", iAsync.IsCompleted); //Console.WriteLine("Sum: {0}", opCode.EndInvoke(iAsync)); Console.WriteLine("Check if Add is complete {0}", iAsync.IsCompleted); ThreadProperties.Basics(); Console.ReadLine(); }
public ExprBinary(Ctx ctx, BinaryOp op, TypeReference type, Expr left, Expr right) : base(ctx) { this.Op = op; this.type = type; this.Left = left; this.Right = right; }
static void WaitCall() { Console.WriteLine("***** Async Delegate Review *****"); // Print out the ID of the executing thread. Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId); // Invoke Add() in a asynchronous manner. BinaryOp b = new BinaryOp(Add); IAsyncResult res = b.BeginInvoke(10, 10, null, null); //while (!res.IsCompleted) //{ // Console.WriteLine("Doing more work in Main()!"); // Thread.Sleep(1000); //} while (!res.AsyncWaitHandle.WaitOne(1000, true)) { Console.WriteLine("Doing more work in Main()!"); } //Obtain results from Add int answer = b.EndInvoke(res); Console.WriteLine("10 + 10 is {0}.", answer); }
static void Main(string[] args) { Console.WriteLine("***** Async Delegate Invocation *****"); // Print out the ID of the executing thread. Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); IAsyncResult iftAR = b.BeginInvoke(10, 10, null, null); // This message will keep printing until // the Add() method is finished. while (!iftAR.IsCompleted) { Console.WriteLine("Doing more work in Main()!"); Thread.Sleep(1000); } // Now we know the Add() method is complete. int answer = b.EndInvoke(iftAR); Console.WriteLine("10 + 10 is {0}.", answer); Console.ReadLine(); }
//Fold arithmetic and bitwise operations public override void Visit(BinaryOp<int, TypedExpression<int>> node) { if (node.Left is Number && node.Right is Number) { Console.WriteLine("Folding {0} into {1}", node, node.TypedValue); int pos = node.Parent.ChildNodes.IndexOf(node); node.Parent[pos] = new Number(node.TypedValue); } }
public BinaryExpression(AbstractExpression exp, BinaryOp op, string yVarName) { _xExp = exp; _yVarName = yVarName; _op = op; _scenario = Scenario.ExpVar; }
public BinaryExpression(AbstractExpression xExp, BinaryOp op, AbstractExpression yExp) { _xExp = xExp; _yExp = xExp; _op = op; _scenario = Scenario.ExpExp; }
public static void Main() { BinaryOp b = new BinaryOp(SimpleMath.Add); // b(10,5) �ϸ� �����δ� b.Invoke(15,5) �� ���� Console.WriteLine("b(10,5) = {0}",b(10,5)); // = 15 b = new BinaryOp(SimpleMath.Subtract); Console.WriteLine("b(10,5) = {0}", b(10,5)); // = 5 }
static void Main(string[] args) { Console.WriteLine("Main() thread id: {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp opCode = new BinaryOp(Add); //AsyncCallback delegate opCode.BeginInvoke(30, 40, new AsyncCallback(AddComplete), null); Console.ReadLine(); }
public void AddOperation() { var d = new BinaryOp(SimpleMath.Add); //static method //var d2 = new BinaryOp(SimpleMath.SquareNumber); // <-- compile-time error! it is type safe! DisplayDelegateInfo(d); Console.WriteLine("10 + 10 is {0}", d(10, 10)); Console.WriteLine("10 + 10 is {0}", d.Invoke(10, 10)); // it is equivalent }
public static void Main (string[] args) { Console.WriteLine ("**Simple Delegate Example**\n"); BinaryOp binary = new BinaryOp(SimpleMath.Add);// create BinaryOp delegate obj 'points to' SimpleMath.Add DisplayDelegateInfo(binary); //invoke Add() Console.WriteLine("10 + 10 = {0}", BinaryOp(10, 10)); Console.ReadLine(); }
private static void DelegateSync() { Console.WriteLine("***** Synch Delegate Review *****"); Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); int answer = b(10, 10); Console.WriteLine("Doing more work in Main()"); Console.WriteLine("10 + 10 is {0}", answer); Console.ReadLine(); }
public static int Test_1() { var s = new BinaryOp(Substract); s += Summ; s += Substract; s += Summ; Console.WriteLine($"s(5,7) = {s(5, 7)}"); s -= Summ; Console.WriteLine($"s(5,7) = {s(5, 7)}"); return 0; }
static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); BinaryOp b = new BinaryOp(SimpleMath.Add); Console.WriteLine("10 + 10 is {0}", b(10, 10)); DisplayDelegateInfo(b); Console.ReadLine(); }
public BinaryExpression(string xVarName, BinaryOp op, AbstractExpression exp) { if (string.IsNullOrEmpty(xVarName) || exp == null) { throw new ArgumentNullException(); } _xVarName = xVarName; _yExp = exp; _op = op; _scenario = Scenario.VarExp; }
public BinaryExpression(string xVarName, BinaryOp op, string yVarName) { if (string.IsNullOrEmpty(xVarName) || string.IsNullOrEmpty(yVarName)) { throw new ArgumentNullException(); } _xVarName = xVarName; _yVarName = yVarName; _op = op; _scenario = Scenario.VarVar; }
static void Main(string[] args) { BinaryOp b = new BinaryOp(SimpleMath.Add); Console.WriteLine("10 + 10 is {0}", b(10,10)); Console.WriteLine("10 + 10 is {0}", b.Invoke(10, 10)); //Also ok Console.WriteLine(); DisplayDelegateInfo(b); SimpleMath m = new SimpleMath(); BinaryOp bInst = new BinaryOp(m.Subtract); DisplayDelegateInfo(bInst); Console.ReadLine(); }
public BinaryOperation() { Console.WriteLine("***********Sync Delegate Review**********"); ReadThread("Constructor Invoked"); BinaryOp binOp = new BinaryOp(Addition); int x = 10; int y = 20; //UseBeginInvoke(binOp, x, y); //UseBasicCall(binOp, x, y); UseASyncCallBack(binOp, x, y); }
static void Main(string[] args) { // Create a BinaryOp delegate object that "points to" Simple.Add(). SimpleMath m = new SimpleMath(); BinaryOp b = new BinaryOp(m.Add); // Invoke Add() method indirectly using delegate object. Console.WriteLine("10 + 10 is {0}", b(10,10)); // Display the methods that the delegate is pointing to. And, display the classes defining those methods DisplayDeleateInfo(b); Console.ReadLine(); }
static void SyncCall() { Console.WriteLine("***** Sync Delegate Review *****"); // Print out the ID of the executing thread. Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId); // Invoke Add() in a synchronous manner. BinaryOp b = new BinaryOp(Add); // Could also write b.Invoke(10, 10); int answer = b(10, 10); // These lines will not execute until // the Add() method has completed. Console.WriteLine("Doing more work in Main()!"); Console.WriteLine("10 + 10 is {0}.", answer); }
public static void AsyncDelegate() { Console.WriteLine("AsyncDelegate() on thread Id: {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); IAsyncResult iar = b.BeginInvoke(1, 2, null, null); //while (!iar.IsCompleted) { // Console.WriteLine("doing more foreground work..."); // Thread.Sleep(1000); //} while (!iar.AsyncWaitHandle.WaitOne(1000, true)) { Console.WriteLine("doing more foreground work..."); } int z = b.EndInvoke(iar); Console.WriteLine("AsyncDelegate() z = {0}", z); }
static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); // Create a BinaryOp delegate object that // "points to" SimpleMath.Add(). SimpleMath m = new SimpleMath(); BinaryOp b = new BinaryOp(m.Add); // Invoke Add() method indirectly using delegate object. Console.WriteLine("10 + 10 is {0}", b(10, 10)); DisplayDelegateInfo(b); Console.ReadKey(); }
static void Main(string[] args) { Console.WriteLine("Async callback delegate"); Console.WriteLine("Main invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); IAsyncResult iftAR = b.BeginInvoke(10, 10, new AsyncCallback(AddComplete), "custom state object"); while (!isDone) { Thread.Sleep(1000); Console.WriteLine("-> Doing more work in main"); } Console.WriteLine("Done..."); Console.ReadLine(); }
static void Main(string[] args) { AddSubtractTwoNumbers asm = new AddSubtractTwoNumbers(); BinaryOp a = new BinaryOp(asm.AddMethod); a(10, 5); //BinaryOp b = new BinaryOp(asm.SubtractMethod); a += asm.SubtractMethod; a(10, 5); //Console.WriteLine("10 + 5 equals {0}", a(10,5)); //Console.WriteLine("10 - 5 equals {0}", a(10, 5)); //GetDelegateDetails(a); //Console.WriteLine(); //GetDelegateDetails(a); Console.ReadKey(); }
void DoProggy() { callBack = Add; callBack += Sub; foreach (Delegate d in callBack.GetInvocationList()) { Console.WriteLine("Method Name[" + d.Method + "]"); Console.WriteLine("Type Name[" + d.Target + "]"); } // do the responsible thing :) if(callBack != null) { callBack(4, 5); } }
static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); // Create a BinaryOp delegate object that // "points to" SimpleMath.Add(). BinaryOp b = new BinaryOp(SimpleMath.Add); // Invoke Add() method indirectly using delegate object. Console.WriteLine("10 + 10 is {0}", b(10, 10)); Console.ReadLine(); string[] s1 = { "Hello", "World" }; Console.WriteLine("{0} {1}", s1); StringUtils.Case(s1, StringUtils.Lower); Console.WriteLine("{0} {1}", s1); StringUtils.Case(s1, StringUtils.Upper); Console.WriteLine("{0} {1}", s1); }
public static void Main (string[] args) { Console.WriteLine ("** AsyncCallbackDelegate Example **"); Console.WriteLine ("Main() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp (Add); IAsyncResult iftAR = b.BeginInvoke (10, 10, new AsyncCallback (AddComplete), "Main() thanks you for adding these numbers."); while (!isDone) { Thread.Sleep(1000); Console.WriteLine("Working..."); } Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("***** AsyncCallbackDelegate Example *****"); Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); IAsyncResult iftAR = b.BeginInvoke(10, 10, new AsyncCallback(AddComplete), "Thanks for this numbers."); // Assume other work is performed here... while (!isDone) { Thread.Sleep(1000); Console.WriteLine("Working...."); } Console.ReadLine(); }
public static void Main(string[] args) { Console.WriteLine("** Sync Delegate Review **"); Console.WriteLine("Main() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); IAsyncResult iftAR = b.BeginInvoke(10, 10, null, null); // int answer = b(10, 10); while (!iftAR.IsCompleted) { Console.WriteLine("Doing more work in Main()"); Thread.Sleep(1000); } int answer = b.EndInvoke(iftAR); // Console.WriteLine("Doing more work in main()"); Console.WriteLine("10 + 10 is {0}", answer); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("***** AsyncCallbackDelegate Example *****"); Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); IAsyncResult ar = b.BeginInvoke(10, 10, new AsyncCallback(AddComplete), "Main() thanks you for adding these numbers."); // Assume other work is performed here... while (!isDone) { Thread.Sleep(1000); Console.WriteLine("Working...."); } Console.WriteLine("Finally done!"); Console.ReadLine(); }
static void UseDelegate() { BinaryOp op = new BinaryOp(Add); foreach (var v in op.GetInvocationList()) { Console.WriteLine("Method {0}", v.Method); Console.WriteLine("GetType {0}", v.GetType()); Console.WriteLine("Target {0}", v.Target); } Console.WriteLine(); op += Sub; foreach (var v in op.GetInvocationList()) { Console.WriteLine("Method {0}", v.Method); Console.WriteLine("GetType {0}", v.GetType()); Console.WriteLine("Target {0}", v.Target); } Console.WriteLine(); op -= Add; foreach (var v in op.GetInvocationList()) { Console.WriteLine("Method {0}", v.Method); Console.WriteLine("GetType {0}", v.GetType()); Console.WriteLine("Target {0}", v.Target); } Console.WriteLine(); foreach (var v in op.GetInvocationList()) { Console.WriteLine("Method {0}", ((BinaryOp)v)(10, 100)); } Console.WriteLine(); }
public void ThreadsWithDelegates() { BinaryOp delegateAsync = new BinaryOp((a, b) => { Console.WriteLine("Enter async delegate"); Thread.Sleep(5000); Console.WriteLine("Exit async delegate"); return(a | b); }); var iAsyncRes = delegateAsync.BeginInvoke(2, 5, null, null); //call delegate async in thread pool Console.WriteLine("Not async delegate"); Console.WriteLine($"You can check IsCompleted at any time. IsCompleted = {iAsyncRes.IsCompleted}"); int returnValue = delegateAsync.EndInvoke(iAsyncRes); //will wait until return from async Console.WriteLine($"Call result = {returnValue}"); }
public static void Main(string[] args) { Console.WriteLine("Main invoked on thread: {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp myAddOp = new BinaryOp(Add); // compute result on secondary thread IAsyncResult ar = myAddOp.BeginInvoke(10, 5, new AsyncCallback(OnAddComplete), null); // do work until the secondary thread is completed while (!isDone) { Console.WriteLine("Doing more work in Main()"); Thread.Sleep(1000); } // obtain the result int result = myAddOp.EndInvoke(ar); Console.WriteLine("Here's the result: {0}", result); Console.ReadKey(); }
static void Main() { WriteLine("***** Async Delegate Invocation *****"); // Print out the ID of the executing thread. WriteLine($"Main() invoked on thread {CurrentThread.ManagedThreadId}."); // Invoke Add() on a secondary thread. BinaryOp b = new BinaryOp(Add); IAsyncResult ar = b.BeginInvoke(10, 10, null, null); // This message will keep printing until the Add() method is finished. while (!ar.AsyncWaitHandle.WaitOne(1000, true)) { WriteLine("Doing more work in Main()!"); } // Obtain the result of the Add() method when ready. int answer = b.EndInvoke(ar); WriteLine($"10 + 10 is {answer}."); ReadLine(); }
IExpression ParseConcatOp(ParseTreeNode node) { if (node.Term.Name == "ConcatOp") { ParseTreeNode left = node.ChildNodes[0]; IExpression lexpr = ParseAddOp(left); if (node.ChildNodes[1].ChildNodes.Count == 0) { return(lexpr); } string opstring = node.ChildNodes[1].ChildNodes[0].Token.ValueString; BinaryOp op = BinaryOp.Concat; ParseTreeNode right = node.ChildNodes[1].ChildNodes[1]; IExpression rexpr = ParseAddOp(right); return(new BinaryExpression() { Left = lexpr, Right = rexpr, Operation = op }); } throw new Exception("Invalid ConcatOp node"); }
static void Main(string[] args) { Console.WriteLine("***** Synch Delegate Review *****"); // Print out the ID of the executing thread. Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId); // Invoke Add() in a synchronous manner. BinaryOp b = new BinaryOp(Add); //Console.WriteLine("After BinaryOp"); // Could also write b.Invoke(10, 10); int answer = b(10, 10); //int answer = Add(10, 20); // not using delegate // These lines will not execute until // the Add() method has completed. Console.WriteLine("Doing more work in Main()!"); Console.WriteLine("10 + 10 is {0}.", answer); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("***** Async Delegate Incovation *****"); //print out the ID of the executing thread Console.WriteLine($"Main() invoked on thread {Thread.CurrentThread.ManagedThreadId}"); //Invoke Add() on a secondary thread BinaryOp b = new BinaryOp(Add); IAsyncResult ar = b.BeginInvoke(10, 10, null, null); //Do other work on primary thread... while (!ar.IsCompleted) { Console.WriteLine($"Doing more work in Main()! #"); Thread.Sleep(1000); } //Obtain the result of the Add() //method when ready int answer = b.EndInvoke(ar); Console.WriteLine($"10 + 10 is {answer}"); }
// The callback method must have the same signature as the // AsyncCallback delegate. // Will be called after BeginInvoke ending async in secondary thread! private static void CallbackMethod(IAsyncResult ar) { // Retrieve the delegate. AsyncResult result = (AsyncResult)ar; BinaryOp caller = result.AsyncDelegate as BinaryOp; // Retrieve the string that was passed as state // information. string someMessage = (string)ar.AsyncState; Console.WriteLine(someMessage); // Define a variable to receive the value of the out parameter. // If the parameter were ref rather than out then it would have to // be a class-level field so it could also be passed to BeginInvoke. int threadId = 0; // Call EndInvoke to retrieve the results. int returnValue = caller.EndInvoke(ar); // Use the format string to format the output message. Console.WriteLine($"Call result = {returnValue}"); }
static void Main(string[] args) { Console.WriteLine("Please enter a number to add"); globalInput1 = Console.ReadLine(); // assume data is OK for simplicity int res = addOperation(5); Console.WriteLine("result of adding 5 to the input is: {0}", res); Console.WriteLine("Please enter another number to add"); string Input2 = Console.ReadLine(); Action action = delegate() { Console.WriteLine("in annon delegate, see how we can work with the input"); Console.WriteLine(Input2); }; // this was not active code. Nothing will happen till next command. action.Invoke(); BinaryOp delOperation = delegate(int a) { Console.WriteLine("in annon delegate delOperation"); int numToAdd = int.Parse(Input2); return(a - numToAdd); }; // this was not active code. Nothing will happen till next command. delOperation(5); }
static void Main(string[] args) { Console.WriteLine($"Main() executed on thread #{Thread.CurrentThread.ManagedThreadId}"); BinaryOp op = Add; //int result = op.Invoke(10, 10); // Thread thread = new Thread(Add); IAsyncResult asyncResult = op.BeginInvoke(10, 10, DelegateFinished, "Kind regards from Main()"); //while (!asyncResult.IsCompleted) //{ // Console.Write("."); // Thread.Sleep(200); //} //Console.WriteLine(); //while (!asyncResult.AsyncWaitHandle.WaitOne(20000, true)) //{ // Console.Write("."); //} //Console.WriteLine(); while (!isDone) { Console.Write("."); Thread.Sleep(200); } Console.WriteLine(); // thread.Join(); // int result = op.EndInvoke(asyncResult); // Console.WriteLine($"The result of 10 + 10 is: {result} (thread #{Thread.CurrentThread.ManagedThreadId})"); Console.ReadLine(); }
public void TestExpression() { var input = "12 * 3 + foo(-3, x)() * (2 + 1)"; var expected = new BinaryOp( BinaryOperatorType.Add, new BinaryOp( BinaryOperatorType.Mul, new Literal(12), new Literal(3) ), new BinaryOp( BinaryOperatorType.Mul, new Call( new Call( new Identifier("foo"), ImmutableArray.Create <IExpr>( new UnaryOp(UnaryOperatorType.Neg, new Literal(3)), new Identifier("x") ) ), ImmutableArray.Create <IExpr>() ), new BinaryOp( BinaryOperatorType.Add, new Literal(2), new Literal(1) ) ) ); Assert.Equal(new ExprParser().ParseOrThrow(input), expected); }
private string GetString(BinaryOp op) { switch (op) { case BinaryOp.Or: return(" or "); case BinaryOp.And: return(" and "); case BinaryOp.Add: return(" + "); case BinaryOp.Sub: return(" - "); case BinaryOp.Mul: return(" * "); case BinaryOp.Div: return(" / "); case BinaryOp.Mod: return(" % "); case BinaryOp.Power: return(" ^ "); case BinaryOp.Error: return(" <err> "); default: Contracts.Assert(false); return(" <bad> "); } }
static void Main(string[] args) { Console.WriteLine("***** Async Delegate Invocation *****"); // Print out the ID of the executing thread. Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId); // Invoke Add() on a secondary thread. BinaryOp b = new BinaryOp(Add); IAsyncResult iftAR = b.BeginInvoke(10, 10, null, null); // This message will keep printing until // the Add() method is finished. while (!iftAR.AsyncWaitHandle.WaitOne(1000, true)) { Console.WriteLine("Doing more work in Main()!"); } // Now we know the Add() method is complete. int answer = b.EndInvoke(iftAR); Console.WriteLine("10 + 10 is {0}.", answer); Console.ReadLine(); }
private int PrecedenceLevel(BinaryOp op) { switch (op) { case BinaryOp.Multiply: case BinaryOp.Divide: case BinaryOp.Modulus: case BinaryOp.ShiftLeft: case BinaryOp.ShiftRight: case BinaryOp.And: case BinaryOp.AndNot: return(5); case BinaryOp.Add: case BinaryOp.Subtract: case BinaryOp.Or: case BinaryOp.Xor: return(4); case BinaryOp.LogicalEquals: case BinaryOp.NotEquals: case BinaryOp.LessThan: case BinaryOp.LessEqual: case BinaryOp.GreaterThan: case BinaryOp.GreaterEqual: return(3); case BinaryOp.LogicalAnd: return(2); case BinaryOp.LogicalOr: return(1); } return(0); }
//static ManualResetEvent runSignal = new ManualResetEvent(false); static void Main(string[] args) { Console.WriteLine("Main begins on thread {0}.", Thread.CurrentThread.ManagedThreadId); BinaryOp caller = Program.Add; //Initiate the asynchronious call of Addn (on a thread from the thread pool). AsyncResult asyncResult = (AsyncResult)caller.BeginInvoke(10, 20, AddComplete, null); int i = 1; while (!asyncResult.IsCompleted) { if (i % 5000000 == 0) { Console.WriteLine("From main: " + i); } i++; } //runSignal.WaitOne(); //Console.WriteLine("Sum is " + sum); Console.ReadLine(); }
private static void BasicExamples() { BasedAdder badder1 = new BasedAdder(10); BasedAdder badder2 = new BasedAdder(35); /* Criação de 4 instâncias de BinaryOp, a partir de métodos * estáticos ou de instância compatíveis com BinaryOp. * * Ver em CIL o uso da instrução ldftn. */ BinaryOp addV1 = new BinaryOp(Adder.Add); BinaryOp addV2 = new BinaryOp(Sum); BinaryOp addV3 = new BinaryOp(badder1.Add); BinaryOp addV4 = new BinaryOp(badder2.Add); /* Invocação das 4 instâncias de delegate. * * Ver em CIL como as 4 invocações são semelhantes. */ Operate(addV1, 3, 4); Operate(addV2, 3, 4); Operate(addV3, 3, 4); Operate(addV4, 3, 4); }
// 00: ldarg.0 a // 01: ldarg.1 b // 02: add.ovf // 03: ldc.i4.2 // 04: div public void VisitBinary(BinaryOp binary) { do { if (m_offset >= 0) { break; } int i = binary.Index; if (i < 4) { break; } if (!DoMatch(i, Code.Div, Code.Div_Un) || !DoMatch(i - 1, Code.Ldc_I4_2)) { if (!DoMatch(i, Code.Shr, Code.Shr_Un) || !DoMatch(i - 1, Code.Ldc_I4_1)) { break; } } if (!DoMatch(i - 2, Code.Add, Code.Add_Ovf)) { break; } if (!IntegerHelpers.IsIntOperand(m_info, i - 2, 0) || !IntegerHelpers.IsIntOperand(m_info, i - 2, 1)) { break; } m_offset = binary.Untyped.Offset; }while (false); }
static void AddIntBinaryOp(string name, BinaryOp <int> op) { AddOpToNativeFunc(name, 2, ValueType.Int, op); }
static void Main(string[] args) { BinaryOp b = new BinaryOp(SimpleMath.Substract); Console.WriteLine(b(5, 6)); }
protected override void VisitBinaryOp(BinaryOp node, object data) { state.Stack.Perform_BinaryOp(node.Op, node.Overflow, node.Unsigned, out exc); nextNode = node.Next; }
public abstract Result BinaryOperationTyped(BinaryOp op, ResultSingle right);
public Result BinaryOperation(BinaryOp op, Result right) => right.CallMe(op, this);
static void AddStringBinaryOp(string name, BinaryOp <string> op) { AddOpToNativeFunc(name, 2, ValueType.String, op); }
static void AddFloatBinaryOp(string name, BinaryOp <float> op) { AddOpToNativeFunc(name, 2, ValueType.Float, op); }
protected abstract Result CallMe(BinaryOp op, Result left);
public void Visit(BinaryOp node) { VisitLuaFunction(node); }
static void Main(string[] args) { //var tupleLens = Lens<(string, int), int>.Of(s => s.Item2, (a, s) => (s.Item1, a)); //Console.WriteLine(tupleLens.Set(3, ("abc", 2))); ////var prismSubject = Prism<Person, Maybe<Subject>>.Of(s => { return s.IsStudent == true ? Just(s.Subject) : Nothing<Subject>(); }, (a, s) => s.IsStudent == true ? new Person()); BinaryOp rectArea = RectArea; BinaryOp squareArea = SquareArea; BinaryOp comb = rectArea + squareArea; //comb += rectArea; //comb += squareArea; WriteLine("---------------"); //foreach (BinaryOp f in comb.GetInvocationList()) { // WriteLine(f(3, 4)); //} WriteLine(comb(4, 7)); WriteLine("---------------"); //List(1, 2, 3) //.Map(x => x + 1) //.DebugPrint(); //Just(1) // .Map(x => x + 2) // .DebugPrint(); //Right<string, int>(1)because most IDEs can be setup to auto line wrap code for those that prefer it // .Map(x => x + 1) // .DebugPrint(); //Success<string, int>(1) // .Map(x => x + 1) // .DebugPrint(); //Of(1) // .Map(x => x + 1) // .DebugPrint(); //List(1, 2, 3).ToCoyo<List<int>, List<int>>() // .Map(xs => xs.Map(x => x.ToString() + " World!")) // .Run() // .DebugPrint(); //List(1).ToYoneda<int>() //.Map(x => x + 1) //.RunIEnumerable() //.DebugPrint(); //Console.WriteLine("Hello World!"); //var read = IO<string>.Of(() => Console.ReadLine()); //var write = Fun<string, IO<int>>(v => IO<int>.Of(() => { // Console.WriteLine(v); // return 0; //})); //var blah1 = from _1 in write("What's your name?") // from name in read // from _2 in write($"Hi {name}, what's your surname?") // from surname in read // select $"{name} {surname}"; //var blah2 = Fun(() => { // Console.WriteLine("What's your name?"); // var name = Console.ReadLine(); // Console.WriteLine($"Hi {name}, what's your surname?"); // var surname = Console.ReadLine(); // return $"{name} {surname}"; //}); //Console.WriteLine(blah2()); //Console.WriteLine(blah1.Compute()); //var pgm2 = Fun<int, string, int, string, string>((u, v, w, x) => $"{v} {x}") // .LiftM(write("What is your name?"), read, write("what's your surname?"), read); //Console.WriteLine(pgm2.Compute()); //var firstname = "Jack"; //var lastname = "Sprat"; //Func<string, string> title = prefix => { // return $"{prefix} {firstname}, {lastname}"; //}; //Console.WriteLine(title("Mr")); // "Mr Jack, Sprat" string greeting = ""; Action <string> greet = name => { greeting = $"Hi, {name}"; }; greet("Brian"); Console.WriteLine(greeting); // "Hi, Brian" //var abs = Math.Abs(Math.Abs(-3)); //var input = new List<int> { 2, 1, 3, 4, 6, 5 }; //Func<int, int> id = x => x; //var output = input.Map(id); //output.DebugPrint(); IEnumerable <T> AlternationOf <T>(Func <int, T> fn, int n) => Enumerable.Range(n, n).Select(fn); //string VowelPattern(int v) => "aeiou".ToCharArray().Map(x => x.ToString()).ToList()[v % 5]; string BinaryPattern(int v) => (v % 2).ToString(); IEnumerable <string> BinaryAlternation(int n) => AlternationOf(BinaryPattern, n); string BinaryLine(int n) => BinaryAlternation(n).Join(" "); string BinaryTriangle(int n) => Enumerable.Range(1, n).Map(BinaryLine).Join("\n"); string BinarySquare(int n) => Enumerable.Range(1, n).Map(x => BinaryLine(n)).Join("\n"); WriteLine(BinaryLine(3)); WriteLine(BinaryTriangle(4)); WriteLine(BinarySquare(5)); Measure("Functional1", 10, () => { int sum3or5(int a, int e) => (e % 3 == 0 || e % 5 == 0) ? a + e : a; return(Enumerable.Range(0, 1000) .Aggregate(sum3or5)); }); Measure("Functional2", 10, () => { return(Enumerable.Range(0, 1000) .Aggregate((a, e) => e.IsMultipleOf().ForEither(3, 5) ? a + e : a)); }); Measure("Functional3", 10, () => { return(Enumerable.Range(0, 1000) .Where(e => e.IsMultipleOf().ForEither(3, 5)) .Sum()); }); Measure("Imperative1", 10, () => { var total = 0; for (int i = 1; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) { total += i; } } return(total); }); Measure("Imperative2", 10, () => { var total = 0; foreach (var v in Enumerable.Range(0, 1000)) { total += (v % 3 == 0 || v % 5 == 0) ? v : 0; } return(total); }); //var t = Try(() => "test") // .Bind(a => Try<string>(() => throw new Exception())) // .Bind(a => Try(a.ToUpper)); //var numbers = List(List(1), List(2), List(3), List(4), List(5)); var numbers = List(1, 2, 3, 4, 5); //numbers.DebugPrint(); var right = Right <string, string>("success"); right.DebugPrint(); var identity = Of("id1"); identity.DebugPrint(); Person num = null; var maybe = Just(num); maybe.DebugPrint(); var reader = 2.ToReader < string, int > (); reader.DebugPrint(); var validation = Success <string, int>(2); validation.DebugPrint(); var blah = Fun((string a) => WriteLine(a)); blah("Hello World"); var is3or5 = Fun((int a) => a.IsMultipleOf().ForEither(3, 5)); var p = new Point(2, 3); var(x1, y1) = p; var shoppingList = new[] { new { name = "Orange", units = 2.0, price = 10.99, type = "Fruit" }, new { name = "Lemon", units = 1.0, price = 15.99, type = "Fruit" }, new { name = "Apple", units = 4.0, price = 15.99, type = "Fruit" }, new { name = "Fish", units = 1.5, price = 45.99, type = "Meat" }, new { name = "Pork", units = 1.0, price = 38.99, type = "Meat" }, new { name = "Lamb", units = 0.75, price = 56.99, type = "Meat" }, new { name = "Chicken", units = 1.0, price = 35.99, type = "Meat" } }; var ITotal = 0.0; // identity value / seed value for (int i = 0; i < shoppingList.Count(); i++) { if (shoppingList[i].type == "Fruit") // predicate / where { ITotal += shoppingList[i].units * shoppingList[i].price; // reducer / aggregation } } WriteLine($"total = {ITotal}"); var FTotal1 = shoppingList.Fold(0.0, (a, e) => e.type == "Fruit" ? a + e.units * e.price : a); WriteLine($"fruit total = {FTotal1}"); var FTotal2 = shoppingList.Where(x => x.type == "Fruit").Sum(x => x.units * x.price); WriteLine($"fruit total = {FTotal2}"); var Mathematics = Tagged(Subject.Mathematics, 70); var Science = Tagged(Subject.Science, (60, 70, 80)); var Economics = Tagged(Subject.Economics, (60, 70)); var Medicine = Tagged(Subject.Medicine, ("ted", 65, 75.5)); Mathematics .Map(x => x * 1.1) .DebugPrint(); Science .Map(x => (x.Item1 * 1.1, x.Item2 * 1.2, x.Item3 * 1.3)) .DebugPrint(); Economics .DebugPrint(); Economics.Switch(t => t.Tag) .Case(Subject.Mathematics, t => WriteLine($"Mathematics: {t}")) .Case(Subject.Economics, t => WriteLine($"Economics: {t}")) .Case(Subject.Science, t => WriteLine($"Science: {t}")) .Else(_ => WriteLine("Default: No Match")); var res21 = Mathematics.Switch <Tagged <Subject, int>, Subject, int>(t => t.Tag) .Case(Subject.Mathematics, t => { WriteLine($"Mathematics: {t.Value}"); return(t.Value); }) .Case(Subject.Economics, t => { WriteLine($"Economics: {t.Value}"); return(t.Value); }) .Case(Subject.Science, t => { WriteLine($"Science: {t.Value}"); return(t.Value); }) .Else(_ => { WriteLine("Default: No Match"); return(default); });
static void GenerateNativeFunctionsIfNecessary() { if (_nativeFunctions == null) { _nativeFunctions = new Dictionary <string, NativeFunctionCall> (); // Int operations AddIntBinaryOp(Add, (x, y) => x + y); AddIntBinaryOp(Subtract, (x, y) => x - y); AddIntBinaryOp(Multiply, (x, y) => x * y); AddIntBinaryOp(Divide, (x, y) => x / y); AddIntBinaryOp(Mod, (x, y) => x % y); AddIntUnaryOp(Negate, x => - x); AddIntBinaryOp(Equal, (x, y) => x == y ? 1 : 0); AddIntBinaryOp(Greater, (x, y) => x > y ? 1 : 0); AddIntBinaryOp(Less, (x, y) => x < y ? 1 : 0); AddIntBinaryOp(GreaterThanOrEquals, (x, y) => x >= y ? 1 : 0); AddIntBinaryOp(LessThanOrEquals, (x, y) => x <= y ? 1 : 0); AddIntBinaryOp(NotEquals, (x, y) => x != y ? 1 : 0); AddIntUnaryOp(Not, x => (x == 0) ? 1 : 0); AddIntBinaryOp(And, (x, y) => x != 0 && y != 0 ? 1 : 0); AddIntBinaryOp(Or, (x, y) => x != 0 || y != 0 ? 1 : 0); AddIntBinaryOp(Max, (x, y) => Math.Max(x, y)); AddIntBinaryOp(Min, (x, y) => Math.Min(x, y)); // Float operations AddFloatBinaryOp(Add, (x, y) => x + y); AddFloatBinaryOp(Subtract, (x, y) => x - y); AddFloatBinaryOp(Multiply, (x, y) => x * y); AddFloatBinaryOp(Divide, (x, y) => x / y); AddFloatBinaryOp(Mod, (x, y) => x % y); // TODO: Is this the operation we want for floats? AddFloatUnaryOp(Negate, x => - x); AddFloatBinaryOp(Equal, (x, y) => x == y ? (int)1 : (int)0); AddFloatBinaryOp(Greater, (x, y) => x > y ? (int)1 : (int)0); AddFloatBinaryOp(Less, (x, y) => x < y ? (int)1 : (int)0); AddFloatBinaryOp(GreaterThanOrEquals, (x, y) => x >= y ? (int)1 : (int)0); AddFloatBinaryOp(LessThanOrEquals, (x, y) => x <= y ? (int)1 : (int)0); AddFloatBinaryOp(NotEquals, (x, y) => x != y ? (int)1 : (int)0); AddFloatUnaryOp(Not, x => (x == 0.0f) ? (int)1 : (int)0); AddFloatBinaryOp(And, (x, y) => x != 0.0f && y != 0.0f ? (int)1 : (int)0); AddFloatBinaryOp(Or, (x, y) => x != 0.0f || y != 0.0f ? (int)1 : (int)0); AddFloatBinaryOp(Max, (x, y) => Math.Max(x, y)); AddFloatBinaryOp(Min, (x, y) => Math.Min(x, y)); // String operations AddStringBinaryOp(Add, (x, y) => x + y); // concat AddStringBinaryOp(Equal, (x, y) => x.Equals(y) ? (int)1 : (int)0); // Special case: The only operation you can do on divert target values BinaryOp <Path> divertTargetsEqual = (Path d1, Path d2) => { return(d1.Equals(d2) ? 1 : 0); }; AddOpToNativeFunc(Equal, 2, ValueType.DivertTarget, divertTargetsEqual); } }