da*************@gmail.com wrote:
Any idea/modification of AsyncHelper.FireAndForget will be gratly
appreciated.
Basicly I need to call a method with parameters (array of parameters)
and get back array of sorted list or similar...
You will need a method of synchronizing so the place where the result is
needed can wait for the results, I would suggest adding a WaitHandle to
the data-structure passed between the working thread and users.
public abstract class Operation<T> {
protected readonly ManualResetEvent done =
new ManualResetEvent(false);
public WaitHandle Done { get { return done; } }
public ResultType Result {
get {
Done.WaitOne();
return result;
}
}
protected T result;
protected abstract run();
public void Run() {
if ( Done.WaitOne(TimeSpan.Zero, false) )
throw new InvalidOperation("Already ran once");
try {
run();
} finally {
done.Set();
}
}
}
Use this to define operations, like:
public class PlusOperation: Operation {
int x, y;
public PlusOperation(int x, int y) {
this.x = x;
this.y = y;
}
protected override run() { result = x+y; }
}
which you can use as:
int count = 3;
Operation[] operations = new Operation[count];
WaitHandle[] waitfor = new WaitHandle[count];
for ( int i = 0; i < count; ++i ) {
Operation op_i = new PlusOperation(i,-i);
operations[i] = op_i;
waitfor[i] = op_i.Done;
new Thead(new ThreadStart(op_i.Run)).Start();
// or you could use fireandforget
}
WaitHandle.WaitAll(waitfor); // stop untill all are done
int sum;
for ( int i = 0; i < operations.Length; ++i )
sum += operations[i].Result;
--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music:
http://ungdomshus.nu <=-