首页 > 代码库 > C# Threading
C# Threading
Begin/EndInvoke:
Use AsyncCallback EndInvoke to get Result:
public IAsyncResult BeginInvoke(parm ...,AsyncCallback cb, object state);IAsyncResult iar= test.BeginInvoke( 10, //参数 new AsyncCallback((ar) => {
string message = ar.AsyncState; int result = ((TestMethode((AsyncResult)ar).AsyncDelegate).EndInvoke(ar); tb.Text = result.ToString(); }), //callback "test" //state);
//Use EndInvoke to wait //阻塞int result = test.EndInvoke(ar);
ThreadPool:
RegisterWaitForSingleObject: trigger callback if waitObject has signal OR time out:
public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, Object state, int millisecondsTimeOutInterval, bool executeOnlyOnce)
static AutoResetEvent wait=new AutoResetEvent(false);ThreadPool.RegisterWaitForSingleObject(wait, new WaitOrTimerCallback(test11), state,5000, false);//use wait.Set() to run the callback immediately//Otherweise use new AutoResetEvent(true)wait.Set();
Task:
CancellationTokenSource tokenSource = new CancellationTokenSource(); Task<string> task = new Task<string>((obj) => { while (true) { if (ck.IsCancellationRequested) { // Clean up here, then... break; } } return "Done"; }, tokenSource.Token); task.Start();//等待任务的完成执行过程。task.Wait();//获得任务的执行结果Console.WriteLine("任务执行结果:{0}", task.Result.ToString());//cancel the tasktokenSource.Cancel();//User Task.FactoryTask.Factory.StartNew(() => { ProcessFiles(); });
Child-Task:
var parent = Task.Factory.StartNew(() =>{var nonChildTask = Task.Factory.StartNew( () => Console.WriteLine("I‘m not a child task."));var childTask = Task.Factory.StartNew( () => Console.WriteLine("I‘m a child task."), TaskCreationOptions.AttachedToParent);});
OR:
Task parent=new Task(()=>{ DoStep1();});Task task2 = parent.ContinueWith((PrevTask) =>{ DoStep2();});parent.Start();
Cancel Task
1.
token.ThrowIfCancellationRequested();
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。