//程序入口 private void Run() { //实例化委托并初赋值 DelegateName dn = new DelegateName(MethodName); //输出参数 int i; //实例化回调方法 //把AsyncCallback看成Delegate你就懂了,实际上AsyncCallback是一种特殊的Delegate,就像Event似的 AsyncCallback acb = new AsyncCallback(CallBackMethod); //异步开始 //如果参数acb换成null则表示没有回调方法 //最后一个参数dn的地方,可以换成任意对象,该对象可以被回调方法从参数中获取出来,写成null也可以。 //参数dn相当于该线程的ID,如果有多个异步线程,可以都是null,但是绝对不能一样,不能是同一个object,否则异常 IAsyncResult iar = dn.BeginInvoke(1, out i, acb, dn); //去做别的事 //………… using (StreamWriter sw = File.AppendText(@"C:\dsData.txt")) { sw.WriteLine(DateTime.Now.Ticks + "干别的事去喽!"); sw.Flush(); sw.Close(); } }
private static void AsyncWays_NormalSvc() { //实例化委托并初赋值 DelegateName dn = new DelegateName(NormalCompute); //实例化回调方法 AsyncCallback acb = new AsyncCallback(CallBackMethod); //异步开始 //如果参数acb 换成 null 则表示没有回调方法 //最后一个参数 dn 的地方,可以换成任意对象,该对象可以被回调方法从参数中获取出来,写成 null 也可以。参数 dn 相当于该线程的 ID,如果有多个异步线程,可以都是 null,但是绝对不能一样,不能是同一个 object,否则异常 IAsyncResult iar = dn.BeginInvoke(acb, dn); }
public void InvokeHandle(string text) { try { DelegateName dlName = new DelegateName(GetCurrentName); BeginInvoke(dlName, text); } catch (Exception ex) { throw ex; } }
private static void RegisterAndCallDelegates() { string message = "Leandro Andrioli"; // Create an instance of the delegate DelegateName del = new DelegateName(DisplayOne); //Calling the delegate del(message); // Another way if declaration DelegateName delTwo = DisplayTwo; delTwo.Invoke(message); }
static void Main(string[] args) { MyDelegate dlg = new MyDelegate(); dlg.GetName("Shahane"); //int age=MyDelegate.GetAge(24); //WriteLine(age); DelegateName dg = new DelegateName(dlg.GetName); dg("Garik"); DelegateAge gd = new DelegateAge(MyDelegate.GetAge); int age = gd(24); WriteLine(age); }
//程序终点 //异步完成时,执行的方法(回调方法),此方法只能有IAsyncResult一个参数,但是该参数几乎万能,可以传递object private void CallBackMethod(IAsyncResult ar) { //从异步状态ar.AsyncState中,获取委托对象 DelegateName dn = (DelegateName)ar.AsyncState; //输出参数 int i; //一定要EndInvoke,否则你的下场很惨 string r = dn.EndInvoke(out i, ar); using (StreamWriter sw = File.AppendText(@"C:\dsData.txt")) { sw.WriteLine(DateTime.Now.Ticks + Convert.ToString("异步完成喽!i的值是" + i.ToString() + ",r的值是" + r)); sw.Flush(); sw.Close(); } }
static void Main(string[] args) { //wywołuyjemy funkcję: SomeFunction2(SomeFunction1); //przypisanie zmiennej do funkcji: var someVar = new DelegateName(SomeFunction1); // wywołanie zmiennej: someVar(); //funkcje anonimowe, bez towrzenia funkcji "na sztywno", tylko wpisując ją w deklaracji delegata: Delegate2 someVar2 = delegate(int a) { return(2); }; // używając lambda (jest traktowana jako OBIEKT): Delegate2 someVar3 = (int a) => { return(2); }; // po lewej stronie wyrażenia lambda parametry (jak nie ma używamy "()"), po prawej wyrażenie lub blok poleceń // najprosztsza postać: Delegate2 someVar4 = (a) => 2; // zamiast używać delegate public delegate int Delegate2(int a); możemy użyć Action, jeżeli funkcja nic nie zwraca, // albo Func, jeżeli zwraca: Action <int> someVar5 = (a) => { }; Func <int, int> someVar6 = (a) => 5; Func <int, int> someVar7 = (a) => { return(5); }; // praktyczny przykład: var listOfStrings = new List <string> { "a", "b", "c", "d", "e", "f" }; // funkcja -> pierwszy string, który zaczyna się od litery "b", wykorzystamy lambdę" var machingExpression = GetFirstOrDefault(listOfStrings, (someString) => { return(someString.StartsWith("b")); }); Console.WriteLine(machingExpression); }
private void RegisterAndCallMulticastDelegates() { string msg = "Leandro"; //Create delegate DelegateName del = DisplayOne; //Multicast delegate del += DisplayTwo; //calling delegate del(msg); foreach (DelegateName item in del.GetInvocationList()) { //invoke each method, and display return value item(msg); } //remove method's reference del -= DisplayOne; del(msg); }
private void AutoLogin() { string[] lastEmployee = db_EmployeeLoginDao.getLastAutoLogin(); if (lastEmployee != null && lastEmployee[2] == "1") //如果最后一次登录的账号为自动登录 { this.BeginInvoke(new Action(delegate() { cbMember.Checked = true; btnLogin.Enabled = false; tbCard.Text = lastEmployee[0]; })); IAsyncResult r = new DelegateName(new Action(delegate { autoLoginTimer = new System.Timers.Timer(); autoLoginTimer.Interval = 1000; autoLoginTimer.Elapsed += (sender, e) => { if (waittimes > 0) { this.BeginInvoke(new Action(delegate() { _ShowInfo((waittimes - 1) + "秒后自动登录,取消勾选则自动登录取消.", Color.Blue); waittimes--; })); } else { allDone.Set(); } }; autoLoginTimer.Start(); })).BeginInvoke(null, null); allDone.WaitOne(); llgin(lastEmployee); } if (lastEmployee == null || lastEmployee[2] == "0" || MainStaticData.autoLoginSucc != true) //没有自动登录的账户,弹出登录框, 或者自动登录没有成功,也弹出登录框 { this.Invoke(new Action(delegate() { btnLogin.Enabled = true; if (lastEmployee != null && lastEmployee.Length > 0) { tbCard.Text = lastEmployee[0]; } })); } }
private static void SomeFunction2(DelegateName delegateName) { }
private void btnUpdate_Click(object sender, EventArgs e) { try { if (isRunning == false) { prgUpdate.Value = 0; int totals = 0; int updated = 0; int updateError = 0; lblMovie.Text = ""; if (DataOperation.IsConnected() == true) { bool ignore = chkIgnore.Checked; bool image = chkImage.Checked; bool rate = chkRate.Checked; bool link = chkLink.Checked; bool year = chkYear.Checked; bool duration = chkDuration.Checked; bool story = chkStory.Checked; bool genre = chkGenre.Checked; bool director = chkDirector.Checked; bool directorPhoto = chkDirectorPhoto.Checked; bool actor = chkActors.Checked; bool actorPhoto = chkActorPhoto.Checked; bool language = chkLanguage.Checked; DateTime?fromDate = null; DateTime?toDate = null; if (this.datePickFrom.Checked) { fromDate = this.datePickFrom.Value; } if (this.datePickTo.Checked) { toDate = this.datePickTo.Value; } DataTable dtMovies = new DataTable(); if (image == true || rate == true || link == true || year == true || duration == true || story == true || genre == true || director == true || directorPhoto == true || language == true || actor == true || actorPhoto == true) { string logName = "iMovie Update Log [" + Helper.GetShortDateTimeString().Replace(":", "-") + "].txt"; iMovieBase.log.Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), logName); dtMovies = Movie_SP.GetList(true, fromDate, toDate); Movie[] movieList = Movie.FetchAllMovie(dtMovies); prgUpdate.Maximum = movieList.Length; SecondThread = new Thread( new ThreadStart(() => { try { enUpdateResult result = enUpdateResult.UpdateError; int BannedIP = 0; int ConnectionLost = 0; int UpdateError = 0; isRunning = true; this.exitRequest = false; foreach (Movie m in movieList) { if (this.exitRequest == false) { totals++; DelegateName dlName = new DelegateName(GetCurrentName); BeginInvoke(dlName, "Updating: " + m.FullTitle); result = Movie_SP.UpdateOnline(m, image, rate, link, year, duration, story, genre, director, directorPhoto, language, actor, actorPhoto, ignore, true, false, null); if (result == enUpdateResult.Updated) { updated++; } else if (result == enUpdateResult.NotOpen || result == enUpdateResult.UpdateError) { updateError++; } if (result == enUpdateResult.NotOpen) { if (DataOperation.IsConnected() == true) { BannedIP++; ConnectionLost = 0; } else { ConnectionLost++; BannedIP = 0; } } if (result == enUpdateResult.UpdateError) { UpdateError++; } else if (result != enUpdateResult.NoNeedUpdate && result != enUpdateResult.UpdateError) { UpdateError = 0; } if (chkWarn.Checked == true) { if (UpdateError >= 20) { if (MessageBox.Show(Messages.CheckInternet.Replace(@"\n", Environment.NewLine).Replace("@NUM@", UpdateError.ToString()), Messages.MessageBoxTitle, MessageBoxButtons.RetryCancel, MessageBoxIcon.Question) == DialogResult.Cancel) { this.exitRequest = true; } UpdateError = 0; } else if (ConnectionLost >= 8) { MessageBox.Show(Messages.NotConnected, Messages.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); ConnectionLost = 0; } else if (BannedIP >= 10) { if (MessageBox.Show(Messages.IPBanned.Replace(@"\n", Environment.NewLine).Replace("@NUM@", BannedIP.ToString()), Messages.MessageBoxTitle, MessageBoxButtons.RetryCancel, MessageBoxIcon.Question) == DialogResult.Cancel) { this.exitRequest = true; } BannedIP = 0; } } RegistryManager.WriteValue(Helper.GetShortDateTimeString(m.AddDate), Messages.RootKey, Messages.SubKeyLastToArchiveDateTime); } else { break; } InvokeHandle(); } while (prgUpdate.Value < prgUpdate.Maximum) { InvokeHandle(); } DelegateName dlReset = new DelegateName(GetCurrentName); BeginInvoke(dlReset, ""); isRunning = false; this.exitRequest = false; iMovieBase.log.GenerateSilent("Total movies processed: " + totals.ToString() + Environment.NewLine + "Movies updated: " + updated.ToString() + Environment.NewLine + "Movies failed to update: " + updateError.ToString()); MessageBox.Show(Messages.UpdateComplete + Environment.NewLine + Messages.LogCreated + Environment.NewLine + logName, Messages.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } catch (Exception ex) { isRunning = false; exitRequest = false; DelegateName dlResetName = new DelegateName(GetCurrentName); BeginInvoke(dlResetName, ""); DelegateGeneral dlReset = new DelegateGeneral(ResetProgress); BeginInvoke(dlReset); iMovieBase.log.GenerateSilent("Total movies processed: " + totals.ToString() + Environment.NewLine + "Movies updated: " + updated.ToString() + Environment.NewLine + "Movies failed to update: " + updateError.ToString()); MessageBox.Show(Messages.UpdateError + Environment.NewLine + Messages.LogCreated + Environment.NewLine + ex.Message, Messages.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } })); SecondThread.Start(); } else { MessageBox.Show(Messages.SelectValues, Messages.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show(Messages.NotConnected, Messages.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show(Messages.WaitForUpdate, Messages.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception ex) { prgUpdate.Value = 0; MessageBox.Show(ex.Message, Messages.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } }