码迷,mamicode.com
首页 > 其他好文 > 详细

C# Threading

时间:2014-06-20 23:41:27      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   tar   ext   

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 task
tokenSource.Cancel();

//User Task.Factory
Task.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();

 

C# Threading,布布扣,bubuko.com

C# Threading

标签:style   class   blog   code   tar   ext   

原文地址:http://www.cnblogs.com/leihdm/p/3795708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!