简体   繁体   中英

Multiple instances of the same Async task (Windows Phone)

After googeling for ages, and reading some stuff about async task in books. I made a my first program with an async task in it. Only to find out, that i can only start one task. I want to run the task more then once. This is where i found out that that doesn't seem to work. to be a little bit clearer, here are some parts of my code:

InitFunction(var);

This is the Task itself

    public async Task InitFunction(string var)
    {

            _VarHandle = await _AdsClient.GetSymhandleByNameAsync(var);

            _Data = await _AdsClient.ReadAsync<T>(_VarHandle);

            _AdsClient.AddNotificationAsync<T>(_VarHandle, AdsTransmissionMode.OnChange, 1000, this);

    }

This works like a charm when i execute the task only once.. But is there a possibility to run it multiple times. Something like this?

InitFunction(var1); 
InitFunction(var2); 
InitFunction(var3);

Because if i do this now (multiple tasks at once), the task it wants to start is still running, and it throws an exeption.

if someone could help me with this, that would be awesome!

~ Bart

async / await can work perfectly with multiple tasks, and multiple tasks at once. However, sometimes different objects can place restrictions on how many asynchronous operations can be outstanding at one time.

For example, the Ping class can only be used to send one ping at a time. If you want to send multiple pings at once, you need to use multiple Ping instances.

I suspect the same problem is at play here: _AdsClient probably is restricted to a single asynchronous operation at a time. So, if you want multiple InitFunction s to be run at once, you'll have to use multiple instances of whatever type that is.

On the other hand, if you wanted to run InitFunction multiple times, one at a time, then you just need to add some await s to your calling code:

await InitFunction(var1);
await InitFunction(var2);
await InitFunction(var3);

This will probably work - unless _AdsClient has "one-time use" semantics. Some classes do have this restriction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM