public async Task <string> TestMethodAsync(int ID, string name) { myDelegate del = ProcessAsync; var workTask = Task.Run(() => del.Invoke(ID, name)); return(await workTask); }
static void Main(string[] args) { Num[] arr = new Num[10]; for (int i = 0; i < arr.Length; i++) { arr[i] = () => new Num(GetRandom).Invoke(); } myDelegate del = delegate(Num[] c) { double sum = 0; for (int i = 0; i < c.Length; i++) { sum += c[i].Invoke(); } return(sum / c.Length); }; for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i].Invoke()); } Console.WriteLine("Avarage is {0}", del(arr)); Console.ReadKey(); }
/// <summary> /// Control for creatng tables in database with pre-existiong tables /// </summary> /// <param name="exit">Delegate for exiting a process of session creation</param> /// <param name="previousStep">Delegate for previous step of database creation</param> /// <param name="nextStep">Delegate for next step of database creation</param> /// <param name="playerTables">Pre-existing tables</param> /// <param name="conn">Pre-existing connections</param> public DatabaseTablesCreator(myDelegate exit, myDelegate previousStep, myDelegateWithTables nextStep, List <Table> playerTables, List <Table> itemsTables) { InitializeComponent(); registerExit = exit; registerPreviousStep = previousStep; registerNextStep = nextStep; playerTablesToCreate = playerTables; itemsTablesToCreate = itemsTables; if (playerTables.Count == 0) { Table PlayerTable = new Table(); PlayerTable.tableName = "Players"; playerTablesToCreate.Add(PlayerTable); } setCurrentTable("Players", true); showCreatedTable(); rearangeColums(); foreach (Table tab in playerTablesToCreate) { addTableForPlayerToDropDownMenus(tab.tableName); } foreach (Table tab in itemsTablesToCreate) { addTableForItemsToDropDownMenus(tab.tableName); } }
static void SynchronousDelegateSample() { Stopwatch sw = new Stopwatch(); sw.Start(); /* * All the calls to the delegate will be synchronous * This mean that the order will always be 1,2,3,4,5,6 * The thread used will always be the same. */ myDelegate dm = new myDelegate(DelegateMethod); Console.WriteLine(dm(“calling delegate(1) ”)); Console.WriteLine(dm(“calling delegate(2) ”)); Console.WriteLine(dm(“calling delegate(3) ”)); Console.WriteLine(dm(“calling delegate(4) ”)); Console.WriteLine(dm(“calling delegate(5) ”)); Console.WriteLine(dm(“calling delegate(6) ”)); sw.Stop(); Console.WriteLine(“All work was done in : { 0 } milliseconds.nn”, sw.ElapsedMilliseconds); }
delegate void myDelegate(string myString); //?? public void ShowThoseMessages() { myDelegate md = new myDelegate(ShowMessage); // don't need parenth's md += ShowAnotherMessage; //adding to delegate list. md("Chris"); }
public void EndMakeStable(IAsyncResult asyncResult) { AsyncResult r = (AsyncResult)asyncResult; myDelegate lw = (myDelegate)r.AsyncDelegate; lw.EndInvoke(asyncResult); }
public ListenerView(string ip, int port) { _ip = ip; _port = port; myD_ShowMessage = new myDelegate <string>(ShowMessage); InitializeComponent(); }
static void Main(string[] args) { Random rnd = new Random(); myDelegate del1 = () => rnd.Next(1, 100); myDelegate del2 = () => rnd.Next(1, 100); myDelegate del3 = () => rnd.Next(1, 100); myDelegate[] delsA = new myDelegate[] { del1, del2, del3 }; myAdvancedDelegate del4 = (myDelegate[] dels) => { double a = 0; for (int x = 0; x < dels.Length; x++) { int b = dels[x].Invoke(); Console.WriteLine(b); a += b; } return(a / dels.Length); }; Console.WriteLine(del4.Invoke(delsA)); Console.ReadKey(); }
private void Form1_Load(object sender, EventArgs e) { clientSocket = new TcpClient(); clientSocket.Connect("pop.qq.com", 995);//连接到QQ邮箱POP服务器 //建立SSL连接 stream = new SslStream( clientSocket.GetStream(), false, (object sender0, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) => { return(true); //接收所有的远程SSL链接 }); stream.AuthenticateAsClient("pop.qq.com"); //验证 //得到输入流 reader = new StreamReader(stream, Encoding.Default, true); //得到输出流 writer = new StreamWriter(stream); tb_console.Text += ReadMessage(stream) + "\r\n";//reader.ReadLine()+"\r\n"; //代理子线程 myD_ShowMessage = new myDelegate <string>(ShowMessage); }
/// <summary> /// Creator of relations between tables. It can create an connection between two tables /// </summary> /// <param name="exit"> Delegate for exit of database creation</param> /// <param name="previousStep"> Delegate to go back by one step in creation</param> /// <param name="createDatabase"> Delegate for finishing creation of relations and send it to sql creation of database </param> /// <param name="players"></param> /// <param name="connections"> Connections between Player and Items tables to be edited</param> public DatabaseRelationsCreator(myDelegate exit, myDelegateConnectionsDatabase previousStep, myDelegateTreeDatabase createDatabase, List <Table> playerTables, List <Table> itemTables, List <ConnectionsInTables> connections) { InitializeComponent(); registerExit = exit; registerPreviousStep = previousStep; registerCreateDatabase = createDatabase; connectionsToCreate = connections; playerTablesToUse = playerTables; itemTablesToUse = itemTables; if (playerTables.Count > 1) { buttonAddPlayerTables.Visible = true; } else { buttonAddPlayerTables.Visible = false; } if (itemTables.Count > 0) { buttonAddConnectionToItems.Visible = true; } else { buttonAddConnectionToItems.Visible = false; } showConnections(); rearangeControls(); }
static void AsynchronousDelegateSample() { Stopwatch sw = new Stopwatch(); sw.Start(); /* * All the work will be invoked in a blink. * Multiple thread will be used to compute the result of the method. */ myDelegate dm = new myDelegate(DelegateMethod); IAsyncResult result1 = dm.BeginInvoke(“calling delegate(1) ”, null, null); IAsyncResult result2 = dm.BeginInvoke(“calling delegate(2) ”, null, null); IAsyncResult result3 = dm.BeginInvoke(“calling delegate(3) ”, null, null); IAsyncResult result4 = dm.BeginInvoke(“calling delegate(4) ”, null, null); IAsyncResult result5 = dm.BeginInvoke(“calling delegate(5) ”, null, null); IAsyncResult result6 = dm.BeginInvoke(“calling delegate(6) ”, null, null); /* * EndInvoke is synchronous we force to wait for the asynchronous results. */ string r1 = dm.EndInvoke(result1); string r2 = dm.EndInvoke(result2); string r3 = dm.EndInvoke(result3); string r4 = dm.EndInvoke(result4); string r5 = dm.EndInvoke(result5); string r6 = dm.EndInvoke(result6); sw.Stop(); Console.WriteLine(“All asynchronous work was done in : { 0 } ”,
private void longListIsList_LoadData(string currentDir, bool isParent) { try { index = 0; DirectoryInfo di = new DirectoryInfo(currentDir); if (isParent) { currentDirectory = di.Parent.FullName; } else { currentDirectory = currentDir; } myDelegate delegate_1 = new myDelegate(this.load_Directories); myDelegate delegate_2 = new myDelegate(this.load_Files); delegate_1.Invoke(); delegate_2.Invoke(); this.OrderBy(items => items.Type); } catch (UnauthorizedAccessException unauthorizedAccessException) { MessageBox.Show(unauthorizedAccessException.Message); } }
public MainWindow() { Random portGen = new Random(); //portnum = portGen.Next(49152, 65535); portnum = 1200; InitializeComponent(); IPHostEntry host; String hostName = Dns.GetHostName(); host = Dns.GetHostEntry(hostName); TextBox box = textBox; box.Text = ""; foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { box.Text += String.Format("server {0} port {1}\n", ip.ToString(), portnum); } } myDelegate blah = new myDelegate(message); blah.BeginInvoke(null, null); }
static void Main(string[] args) { //싱글라인. myDelegate1 add = (a, b) => a + b; myDelegate2 lamda = () => Console.WriteLine("람다식"); Console.WriteLine("11 + 22 = {0}", add(11, 22)); lamda(); //다중라인.(delegate가 매개변수를 대입 받는 형식으로만, 값리턴 형식으로 X) myDelegate Compare = (a, b) => { if (a > b) { Console.Write("{0}보다 {1}가 크다", b, a); } else if (a < b) { Console.Write("{0}보다 {1}가 크다", a, b); } else { Console.Write("{0}, {1}는 같다", a, b); } }; Compare(11, 22); Console.ReadLine(); Console.ReadKey(); }
private void MainForm_Load(object sender, EventArgs e) { my_textbox.AppendText("Hello\r\n"); mydele = new myDelegate(showValue); mydele += incrementValue; }
public void ReceiveMessage(object clientSocket) { myDelegate d = new myDelegate(updateReceiveTextBox); Socket myClientSocket = (Socket)clientSocket; while(true) { try { int len = myClientSocket.Receive(recvBytes); if (len == 0) { MessageBox.Show("Client left"); myClientSocket.Shutdown(SocketShutdown.Both); myClientSocket.Close(); break; } // this.Dispatcher.Invoke(d, Encoding.ASCII.GetString(recvBytes,0,len)); this.Dispatcher.Invoke(d, Encoding.UTF8.GetString(recvBytes, 0, len)); Thread.Sleep(100); } catch(Exception ex) { this.Dispatcher.Invoke(d, ex.ToString()); } } }
static void Main(string[] args) { //myDelegate d = new myDelegate(method); myDelegate d = method; Console.WriteLine(d(5, 2)); }
public void openOnStart() { isOpen = true; this.renderer.material = openBox; this.renderer.material.color = openColor; clickEvent = empty; }
static void Main(string[] args) { Print print = delegate(int val) { Console.WriteLine("Inside Anonymous method. Value: {0}", val); }; print(100); myDelegate del = delegate(int a, int b) { return(a + b); }; Console.WriteLine(del(10, 10)); int i = 10; Print prnt = delegate(int val) { //Anonymous methods can access variables defined in an outer function, but NOT ref or out paramete of the outer method //It cannot have or access unsafe code //It cannot be used on the left side of the is operator. val += i; Console.WriteLine($"Anonymous method: {val}"); }; prnt(100); del += addNumbers; Console.WriteLine(multiplyNumbers(5, del(6, 9))); }
public static void Funcs() { //anonymous type var myanyType = new { name = "pratik" }; //anonymous method myDelegate mydel = (s) => { s = s + "pratik"; return(s); }; //inline anonymous method myDelegate mydel2 = (s) => s; //Action Action <int> myAction = (a) => { a = 3; }; //inline Action <int> myacAction = (a) => a = 2; EventHandler <EventArgs> myevengHandler = (s, e) => { }; }
void SumCallback(IAsyncResult iar) // I: Interface { // 대리자 함수가 끝났을 때 할 일 AsyncResult ar = iar as AsyncResult; // as: 형 변환하는 역할, iar을 AR객체로 형변환 myDelegate md = ar.AsyncDelegate as myDelegate; object obj = iar.AsyncState; }
static void Main(string[] args) { var myDele = new myDelegate(ConsoleWriter); myDele += FileWriter; var users = new List <User>() { new User() { Name = "Nurlan", Surname = "Huseynov", Age = 20 }, new User() { Name = "Kamal", Surname = "Mirzayev", Age = 22 }, new User() { Name = "Ayxan", Surname = "Enverli", Age = 28 } }; foreach (var item in users) { myDele(item); } var Data = new StreamReader("log.txt"); Console.WriteLine("------------Reader------------"); var myUsers = new List <User>(); var count = 0; while (true) { var reader = Data.ReadLine(); if (reader == null) { break; } var iData = reader.Split(' '); myUsers.Add(new User() { Name = iData[0], Surname = iData[1], Age = int.Parse(iData[2]) }); Console.WriteLine(myUsers[count].FullInfo()); count++; } var search = Console.ReadLine(); var c = myUsers.Where(m => m.Name.ToLower() == search.ToLower()); foreach (var i in c) { Console.WriteLine(i.FullInfo()); } }
private void buttonRight_MouseDown(object sender, MouseEventArgs e) { de = new myDelegate(GoRight); ThreadStart del = new ThreadStart(de); t = new Thread(del); t.Start(); }
public string ExecuteMethod(myDelegate currentDelegate) { while (true) { currentDelegate(); Thread.Sleep(this.interval*1000); } }
public string ExecuteMethod(myDelegate currDelegate) { while (true) { currDelegate(); Thread.Sleep(interval*2000); } }
public static void RepeatAfter(int milisec, myDelegate func) { while (true) { func(); Thread.Sleep(milisec); } }
static void Main(string[] args) { myDelegate example = new myDelegate(myMethod1); example += myMethod2; example += myMethod3; example(); }
static void Main(string[] args) { Illustration I = new Illustration(); myDelegate Obj = new myDelegate(I.func); Obj(); Console.Read(); }
public _06_Events() { myEvent += new myDelegate(sayHi); myEvent += new myDelegate(sayHi2); displayInformation = new DisplayInformation(); displayInformation.DisplayDateAfterEvent += DisplayHello; }
/// <summary> /// 模板窗体 /// </summary> /// <param name="sample"></param> /// <param name="s1">图形最上方中央显示的文字</param> /// <param name="s2">纵坐标显示的文字</param> /// <param name="typeNo">种类:1为1个参数的委托类型;2为2个参数的委托类型</param> public FormModel(myDelegate sample,string s1 ,string s2 , byte typeNo) { mySample = sample ; str1 = s1 ; str2 = s2 ; type = typeNo ; InitializeComponent(); }
public void Running(myDelegate callback) { for (int i = 0; i < 10000; i++) { // does something callback(i); } }
void directWatch() { state = (gameGUI.BasketMode) ? "hand" : "shotgun"; if (pw.end) { clickEvent = empty; } }
public static unsafe void runIt(IntPtr thisptr, IntPtr mem_fun) { Console.WriteLine("Here's C# code:"); myDelegate fun = (myDelegate)Marshal.GetDelegateForFunctionPointer(mem_fun, typeof(myDelegate)); fun(thisptr); // first argument of member functions in C++ is "this", but it's hidden from us :-) }
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { //关键 代理 myDelegate md = new myDelegate(SetText); if (serialPort1.IsOpen == true) { if (serialPort1.BytesToRead == 6) { string readstr = ""; string[] binary = new string[6]; // 二进制字符串数组 int[] cache = new int[6]; // 二进制整形数组 byte[] readBuffer = new byte[6]; string[] Final = new string[6]; // 8位二进制字符窜数组 serialPort1.Read(readBuffer, 0, readBuffer.Length); for (int i = 0; i < 6; i++) { //readstr = readstr + readBuffer[i].ToString("X"); //readstr += readBuffer[i].ToString() + "\n"; readstr += readBuffer[i].ToString() + "\n"; binary[i] = Convert.ToString(readBuffer[i], 2); cache[i] = Convert.ToInt32(binary[i]); Final[i] = string.Format("{0:00000000}", cache[i]); } String Minshiwei = Final[2].Substring(0, 4); String Mingewei = Final[2].Substring(4, 4); int Minshi = Convert.ToInt32(Minshiwei, 2); int Minge = Convert.ToInt32(Mingewei, 2); String Midshiwei = Final[3].Substring(0, 4); String Midgewei = Final[3].Substring(4, 4); int Midshi = Convert.ToInt32(Midshiwei, 2); int Midge = Convert.ToInt32(Midgewei, 2); String Maxshiwei = Final[4].Substring(0, 4); String Maxgewei = Final[4].Substring(4, 4); int Maxshi = Convert.ToInt32(Maxshiwei, 2); int Maxge = Convert.ToInt32(Maxgewei, 2); double FinallNumber = Maxshi * 100 + Maxge * 10 + Midshi * 1 + Midge * 0.1 + Minshi * 0.01 + Minge * 0.001; Invoke(md, FinallNumber.ToString() + "\n"); //serialPort1.Close(); } else { serialPort1.DiscardOutBuffer(); } } }
public static void RepeatAfter(int milisec, myDelegate func) { while (true) { func(); Thread.Sleep(milisec); } }
static void Main() { myDelegate del = new myDelegate(Timer.ShowTime); Show = new EventHandler(del); for (int i = 0; i < 60; i++) { Show.Invoke(); } }
static void Main(string[] args) { string test = " test string 123"; myDelegate a = new myDelegate(reverse); a += removeSpace; a += secondCharUpper; a(test); exercise2 b = new exercise2(add); b += sub; b += div; b += mul; b(5, 15); Console.Read(); }
//?? public void ShowThoseMessages() { myDelegate md = new myDelegate(ShowMessage);// don't need parenth's md += ShowAnotherMessage ;//adding to delegate list. md("Chris"); }
public IAsyncResult BeginMakeStable(LogRecord record, AsyncCallback callback, object asyncState) { myDelegate del = new myDelegate(_makeStable); return del.BeginInvoke(record, callback, asyncState); }
public void useMulticastDelegate() { myDelegate m1 = new myDelegate(method1); myDelegate m2 = new myDelegate(method2); myDelegate m3 = new myDelegate(method3); myDelegate myDelegateMulticast = m1 + m2 + m3; //myDelegate[] allMethodInMyDelegate = (myDelegate[])myDelegateMulticast.GetInvocationList(); //does not work Delegate[] allMethodInMyDelegate = myDelegateMulticast.GetInvocationList(); for (int i = 0; i < allMethodInMyDelegate.Length; ++i) { int returnValue; //we can capture each return value from each delegate returnValue = ((myDelegate)allMethodInMyDelegate[i])(string.Format("{0}, this is the argument string", i)); } }
public int runAddManyNumberDelegate1() { myDelegate md = new myDelegate(addManyNumber); //or, myDelegate md = addManyNumber; //this will return right away IAsyncResult iftAR = md.BeginInvoke("run beginInvoke", null,null ); //busy loop to appreciate the multithreading feeling while (!iftAR.IsCompleted) { Console.WriteLine("MyAsyncDelegate is not completed"); } Console.WriteLine("\n\nMyAsyncDelegate is now compleged"); //calling thread is now blocked until EndInvoke is completed int answer = md.EndInvoke(iftAR); return answer; }
//Calls the passed void function with no arguments after delay public static IEnumerator CallWithDelay(myDelegate del, float delay) { yield return new WaitForSeconds(delay); del(); }
public static int Main_old() { myDelegate[] myDel = new myDelegate[10]; return 0; }
private void receiveLoop() { try { Byte[] l_Buffer; string l_receivedString; while (cliente.Connected) { l_Buffer = new Byte[100]; cliente.Receive(l_Buffer, l_Buffer.Length, SocketFlags.None); l_receivedString = System.Text.Encoding.ASCII.GetString(l_Buffer, 0, l_Buffer.Length); myDelegate updateDelegate = new myDelegate(updateMessageLog); updateDelegate(l_receivedString); } } catch (System.Exception) { //MessageBox.Show(e.ToString()); } }
private void DoWork() { myDelegate d = new myDelegate(ExportData); this.Invoke(d); }