Hi,
the problem with your code is that sayGood is actually a value and not a function. It is evaluated when it is declared (even before the taskBody2 task is created). The value assigned to "sayGood" is unit (because that's what the printfn function returns). The following code should clarify the problem:

let test = 
   printfn "initializing 'test'"
   42
printfn "value of test: %d" test

Note that the "initializing..." string is printed before the "value of..." (because the value of "test") needs to be initialized during the let-binding. To correct this, you need to declare "sayGood" as a function (taking for example unit as an argument). Then you can call it from the lambda function passed as a parameter to task..

Also note that the WaitAll method takes a param-array of tasks that you want to wait for as a parameter (AFAIK calling it without parameters doesn't do anything).

 
// function taking string and returning unit
let sayHello englishText = 
    printfn "%s" englishText
    Thread.Sleep(10000)
    printfn "Again: %s" englishText

// a function taking unit and returning unit
let sayGood () = // note: added "()"
    printfn "I am fine and you?"
    Thread.Sleep(10000)
    printfn "Again: you?"

// Note: we can pass lambda functions directly to StartNew
let t1 = Task.Factory.StartNew(fun () -> sayHello "Hello, World!")
let t2 = Task.Factory.StartNew(fun () -> sayGood ()) // pass unit as an argument here

Task.WaitAll(t1, t2);;
By on 1/18/2010 12:40 PM ()
Hello, Tomasp:
Thank you very much for your code and good explanation.
However, I have tried your code for about 10 times, each time, the t2 seems run before t1. (I mean the order of the first printfn statement for each task)
I think the order of which task appears first should be random, right?
Thanks,
By on 1/18/2010 1:12 PM ()
For me, I would expect random order but would not mind even if one always run first. So long there is a way for me to sequence the task(you may need to check the library).

Just from the code, I would say the sequence is 'undefined' so there is no contract saying which may be run first, completely up to the implementation.
By on 1/18/2010 1:33 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us
Built with WebSharper