How Can I make async operations of my own with WinRT using IAsyncOperation interface? - asynchronous

I am developing a metro application and I want to create some async operations whose my own classes would implement.
I have found just examples of async using WinRT operations (e.g. CreateFileAsync). I do not find any intance where someone is creating a async method and consuming it.

Now you can do it. Look at this:
http://blogs.msdn.com/b/nativeconcurrency/archive/2011/10/27/try-it-now-use-ppl-to-produce-windows-8-asynchronous-operations.aspx
http://code.msdn.microsoft.com/Windows-8-Asynchronous-08009a0d
WinRT Async Production using C++

Use create_async in C++:
IAsyncOperationWithProgress<IBuffer^, unsigned int>^ RandomAccessStream::ReadAsync(IBuffer^ buffer, unsigned int count, InputStreamOptions options)
{
if (buffer == nullptr)
throw ref new InvalidArgumentException;
auto taskProvider = [=](progress_reporter<unsigned int> progress, cancellation_token token)
{
return ReadBytesAsync(buffer, count, token, progress, options);
};
return create_async(taskProvider);
}
Use AsyncInfo.Run in .NET:
public IAsyncOperation<IInfo> Async()
{
return AsyncInfo.Run(_ =>
Task.Run<AType>(async () =>
{
return await DoAsync();
})
);
}

I posted the same question in Microsoft forums and they gave me two replies. The first was:
Hi Claudio,
In the Developer Preview there isn't an easy way to create your own
async operations. We are aware of this shortcoming and are trying to
solve it for the next pubic release. In the meanwhile, you could
design your API as async and we will provide guidance on how to
convert sync to async.
Thanks
Raman Sharma, Visual C++
When I asked for the hard way to do this, another guy, someone responsible for PPL said me:
We’re planning to do a refresh of the sample pack we released a few
weeks ago and add a few samples on creation of async operations. I
expect that it will happen in a couple of weeks or so. If you keep an
eye on our blog at http://blogs.msdn.com/b/nativeconcurrency, you’ll
be the first to know.
As to how hard it is... The general-purpose solution that we’re
contemplating is about 1000 lines of C++ code making copious use of
template metaprogramming. Most of it will be in the header file so you
can explore it yourself. While a less general solution can be less
complex, you will still need to implement a base class, do the state
management, error handling etc. At this moment I can’t go into more
detail, but I will say that you will love how easy it is to author
async operations with PPL – so hang in there!
Artur Laksberg PPL team
Then, there is no solution at that time. Thank you all.

Yes, see Ben Kuhn's //BUILD/ talk: http://channel9.msdn.com/events/BUILD/BUILD2011/PLAT-203T He shows how to build an asynchronous API.
At the current time, there is no good solution for high level (C++/WX) classes. However if you use the low level C++ interfaces, you can use the WRL::AsyncBase class to help build your async interfaces.
Here is documentation about the AsyncBase class.

It is confusing, but there is a difference between WinRT C++ code and WRL. You can use WRL to code to the ABI layer directly. WRL does not use exceptions, but loves templates. The recommend coding style for WinRT is not the same as WRL.
I am not sure if everyone can do this, but using WRL you in general need to implement a class that inherits:
class CreateAysncOp: public RuntimeClass<IAsyncOperation<result_runtime_class*>,AsyncBase<IAsyncCompletedHandler<result_runtime_class*>>
{
...
Then you can use
hr = MakeAndInitialize<CreateAsyncOp, IAsyncOperation<type_foo*>>(...);

C++ WinRT is now the best way to implement WinRT async methods. This uses co_await and co_return, new C++ language features (in the process of standardization). Read the docs on this page.

Related

How to get Axon event-identifier from the event-store

Just a short question here...
by using Axon, we know that AggregateLifecycle#apply(Object) will be doing the event-sourced for us which under the hood going to persist our event into our event-store.
With regards to that matter, how to get the event-identifier (not the aggregate identifier) once we call that particular apply method ?
Thanks
Based on your another answer, let me suggest you a way to follow.
The MessageIdentifier as used by AxonFramework (AF) is nothing more than an UUID generated for each Message you create.
Since you only need to reuse that info, you can pretty much get it from the Message while handling it. To make things easier for you, Axon provides a MessageIdentifierParameterResolver meaning you can simply use it in any #MessageHandler of you (of course, I am assuming you are using Spring as well).
Example:
#EventHandler
public void handle(Event eventToBeForwarded, #MessageIdentifier String messageIdentifier) {
// forward the event to another broker using the given `messageIdentifier`
}
Hope that helps you and make things clear!

Where did LoaderService go?

Upgrading AngleSharp from 0.9.6 to 0.9.9 I have this line of code no longer compiling:
return configuration.With(LoaderService(new[] { requester }));
It complains that LoaderService does not exist in the current context. So what happened to LoaderService? Is there a replacement? Does it still exist but just somewhere else?
Good question. Sorry for being late to the party, but even though you may have solved your problem someone else is having a hard time figuring it out.
LoaderService was essentially just a helper to create a loader. But having a service for anything creating a little thing would be overkill and not scale much. Also AngleSharp.Core would need to define all these. So, instead a generic mechanism was introduced, which allows registering such "creator services" via Func<IBrowsingContext, TService>.
However, to solve your piece of code I guess the following line would do the trick:
return configuration.WithDefaultLoader(requesters: requester);
This registers the default loader creator services (one for documents, one for resources inside documents) with the default options (options involve some middleware etc.).
Under the hood (besides some other things) the following is happening:
// just one example, config.Filter is created based on the passed in options
return configuration.With<IDocumentLoader>(ctx => new DocumentLoader(ctx, config.Filter));

How to access a script after object has spawned?

In unity multiplayer the player prefab spawns after the scene loads, what is the best way to declare scripts that are needed and avoid the NullReferenceException error?
I'm not that familiar with multiplayer myself, but I believe this could be done through GameObject.Find("") and GetComponent.
I also stumbled across FindObjectOfType. I'm not sure if that's what you're looking for, but it doesn't hurt to post it. Good luck.
Instead of letting a script look for when the prefabs have spawned why not letting the prefabs tell the script it has spawned?
It's really hard to give any kind of example when the use-case is not specified.
Really basic example (and since you're going to use it for networking you might have to redo this a lot so you don't trust the client too much):
class ScriptA : Monobehaviour () {
List<GameObject> prefabs;
public void AddPrefab (GameObject Prefab) {
prefabs.Add (Prefab)
}
}
class Prefab : Monobehaviour () {
void Start () {
FindObjectOfType(ScriptA).AddPrefab(gameObject);
}
}
It's not the best example but the point is, you might need to rethink the architecture

How to properly use Task object in .NET

I am working on an ASP .NET MVC 5 application that requires me to use the Task objects that were introduced in .NET 4.0. I am browsing through a few links that give an overview of Task objects. However, I could use a bit of help to check if I am going in the right direction.
Here is the stub that is generated by Visual Studio:
public Task<MyAppUser> FindByNameAsync(string userName) {
throw new System.NotImplementedException();
}
I have written a method called mySearch() that searches through a list. I could use this function for my implementation:
public Task<MyAppUser> FindByNameAsync(string userName) {
MyAppUser val = mySearch(userName);
return Task<MyAppUser>.FromResult<MyAppUser>(val);
}
While this may work, I am thinking I am not really utilizing the Task paradigm properly. Perhaps I can write the code as follows:
public Task<MyAppUser> FindByNameAsync(string userName) {
return Task<MyAppUser>.Factory.StartNew(() => mySearch(userName));
}
As I understand, I am simply returning a delegate as a Task object which the ASP.NET engine will execute as needed.
Am I using the Task paradigm correctly?
Don't ever return a new Task from an XXXAsync method - that's almost the worst thing you can do. In your case, using Task.FromResult is probably the best option (if you are indeed forced to use the XXXAsync methods and if you really don't have asynchronous I/O for the search method). In a web application, it's better to do the whole thing synchronously rather than appearing asynchronous while still taking up a different thread.
The reasoning is simple - asynchronous methods are a great way to conserve resources. Asynchronous I/O doesn't require a thread, so you can afford to reuse the current thread for other work until the data is actually ready. In ASP.NET, the callback will be posted back to a ThreadPool thread, so you've managed to increase your throughput essentially for free.
If you fake the asynchronous method by using Task.FromResult, it's true that this is lost. However, unlike in WinForms or WPF, you're not freezing the GUI, so there's no point in masking the lacking asynchronicity by spawning a new thread.
When you do the faking by using TaskFactory.StartNew or Task.Run, you're only making things worse, essentially - it's true that you release the original thread as with proper async I/O, but you also claim a new thread from the ThreadPool - so you're still blocking one thread, you just added a bunch of extra work for the plumbing.
#Luaan's answer is quite good. I just want to expound on a couple of principles for using async on ASP.NET.
1) Use synchronous method signatures for synchronous work.
I'm not sure why VS is generating an asynchronous stub. Since your mySearch just "searches through a list" (a synchronous operation), then your method should look like this instead:
public MyAppUser FindByName(string userName) {
return mySearch(userName);
}
2) Use async/await for asynchronous work (i.e., anything doing I/O). Do not use Task.Run or (even worse) Task.Factory.StartNew to fake asynchronous work within a request context.
For example, if you needed to search in a database (I/O), then that would be naturally asynchronous, and you should use the asynchronous APIs (e.g., EF6 has asynchronous queries):
public Task<MyAppUser> FindByNameAsync(string userName) {
return dbContext.Users.Where(x => x.Name == userName).FirstAsync();
}
If you're planning to have asynchronous APIs but for now you're just doing test/stub code, then you should use FromResult:
public Task<MyAppUser> FindByNameAsync(string userName) {
return Task.FromResult(mySearch(userName));
}

How to change the dart-sqlite code from synchronous style to asynchronous?

I'm trying to use Dart with sqlite, with this project dart-sqlite.
But I found a problem: the API it provides is synchronous style. The code will be looked like:
// Iterating over a result set
var count = c.execute("SELECT * FROM posts LIMIT 10", callback: (row) {
print("${row.title}: ${row.body}");
});
print("Showing ${count} posts.");
With such code, I can't use Dart's future support, and the code will be blocking at sql operations.
I wonder how to change the code to asynchronous style? You can see it defines some native functions here: https://github.com/sam-mccall/dart-sqlite/blob/master/lib/sqlite.dart#L238
_prepare(db, query, statementObject) native 'PrepareStatement';
_reset(statement) native 'Reset';
_bind(statement, params) native 'Bind';
_column_info(statement) native 'ColumnInfo';
_step(statement) native 'Step';
_closeStatement(statement) native 'CloseStatement';
_new(path) native 'New';
_close(handle) native 'Close';
_version() native 'Version';
The native functions are mapped to some c++ functions here: https://github.com/sam-mccall/dart-sqlite/blob/master/src/dart_sqlite.cc
Is it possible to change to asynchronous? If possible, what shall I do?
If not possible, that I have to rewrite it, do I have to rewrite all of:
The dart file
The c++ wrapper file
The actual sqlite driver
UPDATE:
Thanks for #GregLowe's comment, Dart's Completer can convert callback style to future style, which can let me to use Dart's doSomething().then(...) instead of passing a callback function.
But after reading the source of dart-sqlite, I realized that, in the implementation of dart-sqlite, the callback is not event-based:
int execute([params = const [], bool callback(Row)]) {
_checkOpen();
_reset(_statement);
if (params.length > 0) _bind(_statement, params);
var result;
int count = 0;
var info = null;
while ((result = _step(_statement)) is! int) {
count++;
if (info == null) info = new _ResultInfo(_column_info(_statement));
if (callback != null && callback(new Row._internal(count - 1, info, result)) == true) {
result = count;
break;
}
}
// If update affected no rows, count == result == 0
return (count == 0) ? result : count;
}
Even if I use Completer, it won't increase the performance. I think I may have to rewrite the c++ code to make it event-based first.
You should be able to write a wrapper without touching the C++. Have a look at how to use the Completer class in dart:async. Basically you need to create a Completer, return Completer.future immediately, and then call Completer.complete(row) from the existing callback.
Re: update. Have you seen this article, specifically the bit about asynchronous extensions? i.e. If the C++ API is synchronous you can run it in a separate thread, and use messaging to communicate with it. This could be a way to do it.
The big problem you've got is that SQLite is an embedded database; in order to process your query and provide your results, it must do computation (and I/O) in your process. What's more, in order for its transaction handling system to work, it either needs its connection to be in the thread that created it, or for you to run in serialized mode (with a performance hit).
Because these are fairly hard constraints, your plan of switching things to an asynchronous operation mode is unlikely to go well except by using multiple threads. Since using multiple connections complicates things a lot (as you can't share some things between them, such as TEMP TABLEs) let's consider going for a single serialized connection; all activity will be serialized at the DB level, but for an application that doesn't use the DB a lot it will be OK. At the C++ level, you'd be talking about calling that execute from another thread and then sending messages back to the caller thread to indicate each row and the completion.
But you'll take a real hit when you do this; in particular, you're committing to only doing one query at a time, as the technique runs into significant problems with semantic effects when you start using two connections at once and the DB forces serialization on you with one connection.
It might be simpler to do the above by putting the synchronous-asynchronous coupling at the Dart level by managing the worker thread and inter-thread communication there. That would let you avoid having to change the C++ code significantly. I don't know Dart well enough to be able to give much advice there.
Myself, I'd just stick with synchronous connection processing so that I can make my application use multi-threaded mode more usefully. I'd be taking the hit with the semantics and giving each thread its own connection (possibly allocated lazily) so that overall speed was better, but I do come from a programming community that regards threads as relatively heavyweight resources, so make of that what you will. (Heavy threads can do things that reduce the number of locks they need that it makes no sense to try to do with light threads; it's about overhead management.)

Resources