0

さまざまなアプリケーションや言語での非同期タスクに問題があります。

私が理解している限り、典型的な使用法は次のようなものです。

asyncTask(x,y){
    //do something
}

alwaysRunWhenAsyncIsFinished(){
    //continue with the app has to 
    //happen here
}

...

mainProgramFunction(){
    asyncTask(5,6);
}

この場合、非同期タスクが発生するまでプログラムを作成する必要があります。また、asyncTaskを呼び出す必要がある場合は、非同期タスクの後に常に最後に発生する関数であるリコール関数に継続コードを記述する必要があります。

このようなものを書く可能性はありますか?

asyncTask(x,y){
    //do something
}


...

mainProgramFunction(){
    asyncTask(5,6);

    continuingCode();//But happens AFTER asyncTask is done.
}

これが可能かどうかは正確にはわかりません。そして、おそらくこれは、この種の非同期タスクを提供する特定のSDKで可能ですか?

最後の選択肢は、非同期タスクとその使用方法を本当に理解していなかったということかもしれません。

4

2 に答える 2

0

Your

 Kick off a task

 Keep doing stuff

model of program structure is supported by many programming languages. For example in Java one can have

 Runnable myRunnable = new MyRunnable();

 new Thread(myRunnable).start();

 doSomeMore();

However this can get a bit messy. You're firing off threads, which presumably may run for an indefinite period of time, so your "main line" may reach its end while the threads are all off doing work. You've got no "supervisory" thread to keep track of that work. Worse, you might end up firing off an excessive number of threads and eat up all processing power.

Hence it's quite common to do all the processing in different threads, an event driven style of programming. So you have a thread listening for events such as worker threads completing and deciding which new workers to create and so on. Or maybe a thread listening for new requests (eg. user's clicking something, or files being created or messages arriving) and deciding whether and when to kick off workers.

In general modern UIs are almost entirely event driven, most of the code is in event handlers (do this when the user clicks that), you don't yourself write a main, the UI framework is in control and calls your code.

I think you'd find it helpful to study a tutorial about event driven programming.

于 2012-09-17T06:37:14.513 に答える
0

mainProgramFunction(){ asyncTask(5,6);

continuingCode();//But happens AFTER asyncTask is done. }

Well, if the continuingCode() must run after asyncTask(), you leave the asynchonous world (-:

But if you need to do something asynchrously, and then wait all the tasks to continue, you can use a semaphore for exemple :

mainProgramFunction(){
    bool taskDone = false;
    asyncTask(5,6);
    doSometingElse();

    while(taskDone != true){
      // wait
    }

    continuingCode();//But happens AFTER asyncTask is done.
}
asyncTask(a,b){
   // compute a and b 
   taskDone = true;
}

(Note that is pseudo code, and each language have good practice on how to to the 'wait' part !).

An other (surely better way) is to use event driven logic...

于 2019-05-28T07:44:57.127 に答える