Asynchronous P / Invoke Calls

I am working on a wrapper library for a robot controller that relies heavily on P / Invoke calls.

However, many functions for the robot, such as homing or moving objects, take a lot of time and perform thread blocking during operation.

So, I am wondering how I can wrap functionality in an asynchronous way, so calls do not block my UI thread. My idea so far is to use Tasks, but I'm not sure if this is the right approach.

public Task<bool> HomeAsync(Axis axis, CancellationToken token) { return Task.Factory.StartNew(() => Home(axis), token); } 

Most MSDN articles in the Async model in .NET at the moment are mainly relayed to libraries that already have Async features (such as File.BeginRead, etc.). But I can not find much information on how to actually write asynchronous functions in the first place.

+6
c #
source share
3 answers

Have you ever tried asynchronous delegates ? I find that nothing is easier.

If your thread locking method is void Home(Axis) , you must first determine the type of delegate, i.e. delegate void HomeDelegate(Axis ax) , then use the BeginInvoke method of a new instance of HomeDelegate pointing to the address of the Home method.

 [DllImport[...]] //PInvoke void Home(Axis x); delegate void HomeDelegate(Axis x); void main() { HomeDelegate d = new HomeDelegate(Home); IAsyncResult ia = d.BeginInvoke(axis, null, null); [...] d.EndInvoke(ia); } 

Please keep in mind that using EndInvoke somewhere (blocking the thread until the method completes completely, perhaps in conjunction with polling the IAsyncResult.Completed property) it is very useful to check if your async task is really complete. You may not want your robot to open its hand and leave the glass until the glass is above the table, you know -)

+4
source share

After a great discussion, I think something like this will be the middle ground.

 public void HomeAsync(Axis axis, Action<bool> callback) { Task.Factory .StartNew(() => Home(axis)) .ContinueWith(task => callback(task.Result)); } 

I use the best of both worlds.

+3
source share

My first reaction is that this is not what you should do in the library. The main reason is that the way you implement such a system may depend on the type of interface you are building on the library.

However, you have basically two options. First up is IAsyncResult . A good description of this can be found at http://ondotnet.com/pub/a/dotnet/2003/02/24/asyncdelegates.html .

The second option is to create teams with callback events. The user creates a class of commands and sets a callback for him. Then you plan the ThreadPool command and after executing the command you raise this event.

Older .NET platform interfaces basically implement the IAsyncResult approach, where newer interfaces tend to implement an event callback approach.

+1
source share

All Articles