简体   繁体   English

同一异步任务的多个实例(Windows Phone)

[英]Multiple instances of the same Async task (Windows Phone)

After googeling for ages, and reading some stuff about async task in books. 经过多年的googeling,并阅读一些关于书中异步任务的东西。 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. 因为如果我现在这样做(一次多个任务),它想要启动的任务仍然在运行,并且它会抛出一个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. async / await可以与多个任务完美配合,同时可以完成多个任务。 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. 例如, Ping类一次只能用于发送一个ping。 If you want to send multiple pings at once, you need to use multiple Ping instances. 如果要一次发送多个ping,则需要使用多个Ping实例。

I suspect the same problem is at play here: _AdsClient probably is restricted to a single asynchronous operation at a time. 我怀疑同样的问题在这里发挥作用: _AdsClient可能一次仅限于一个异步操作。 So, if you want multiple InitFunction s to be run at once, you'll have to use multiple instances of whatever type that is. 因此,如果您希望一次运行多个InitFunction ,则必须使用任何类型的多个实例。

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: 另一方面,如果您想多次运行InitFunction ,一次一个,那么您只需要在调用代码中添加一些await

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

This will probably work - unless _AdsClient has "one-time use" semantics. 这可能会起作用 - 除非_AdsClient具有“一次性使用”语义。 Some classes do have this restriction. 有些课程确实有此限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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