首页 > 代码库 > 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();