Multithread

D

daniele.amberti

I'm trying to write a multithread application:

it will get different kind of data from DB, my intention was to create
different thread for each query.
I tryed to use the AsyncHelper.FireAndForget method u can easily find
on this goup but i wasn't lucky: I was able to crate threads but not to
get back results....

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...

Thanks in advance.
 
H

Helge Jensen

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 = op_i;
waitfor = 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.Result;
 
G

Guest

Another option is to supply the thread with a delegate as an additional
parameter. Once the thread has finished its work then it will call the
delegate, almost similar to raising an event. The query results could then be
passed as a parameter of the delegate.

Yet another option would be to define an interface IQueryListener, and
implement a class that implements that interface. The interface would contain
one method, e.g. OnQueryComplete() and would pass the results as a parameter.
Then you would instantiate that class and pass the reference to that instance
to the thread when it is started.

Kind rgards,
Manfred.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top