コアコンセプト / マルチスレッドモデル

マルチスレッドモデル

NativeScriptの利点の1つは、(非)直列化やリフレクションを使用せずに、JavaScriptを介してすべてのネイティブプラットフォーム(Android / Objective-C)APIにすばやく効率的にアクセスできることです。 ただし、これにはトレードオフがあります。すべてのJavaScriptはメインスレッド(AKA the UI thread)で実行されます。 つまり、時間がかかる可能性がある操作ではUIのレンダリングが遅れ、アプリケーションの外観が遅くなる可能性があります。

UIの鮮明さと高いパフォーマンスが重要な低速性の問題に取り組むために、開発者はネイティブスレッドのマルチスレッドワーカースレッドソリューションを使用できます。 ワーカーは、完全に分離されたコンテキストでバックグラウンドスレッドで実行されるスクリプトです。 実行に時間がかかる可能性があるタスクは、ワーカースレッドにオフロードする必要があります。

NativeScriptのWorkers APIは、Dedicated Web Workers APIWeb Workers Specificationに大まかに基づいています。

ワーカーのAPI

ワーカーオブジェクトプロトタイプ

ワーカーオブジェクトイベントハンドラ

ワーカーグローバルスコープ

ワーカーグローバルスコープのイベントハンドラ

使用例

注釈:consoleメソッド、setTimeout / setInterval、またはcore-modulesパッケージに含まれるその他の機能を使用するには、globalsモジュールを手動でインポートして、新しいワーカースレッド上でインフラを利用可能にする必要があります。

main-view-model.js

...

const WorkerScript = require("nativescript-worker-loader!./worker-script.js");
const worker = new WorkerScript();
worker.postMessage({ src: imageSource, mode: 'scale', options: options });

worker.onmessage = function(msg) {
	if (msg.data.success) {
		// Stop idle animation
		// Update Image View
		// Terminate worker or send another message

		worker.terminate();
	} else {
		// Stop idle animation
		// Display meaningful message
		// Terminate worker or send message with different parameters
	}
}

worker.onerror = function(err) {
	console.log(`An unhandled error occurred in worker: ${err.filename}, line: ${err.lineno} :`);
	console.log(err.message);
}

...

workers / image-processor.js

require('globals'); // necessary to bootstrap tns modules on the new thread

global.onmessage = function(msg) {
	var request = msg.data;
	var src = request.src;
	var mode = request.mode || 'noop'
	var options = request.options;

	var result = processImage(src, mode, options);

	var msg = result !== undefined ? { success: true, src: result } : { }

	global.postMessage(msg);
}

function processImage(src, mode, options) {
	console.log(options); // will throw an exception if `globals` hasn't been imported before this call

	// image processing logic

	// save image, retrieve location

	// return source to processed image
	return updatedImgSrc;
}

// does not handle errors with an `onerror` handler
// errors will propagate directly to the main thread Worker instance

// to handle errors implement the global.onerror handler:
// global.onerror = function(err) {}

ワーカープラグインの詳細については、nativescript-worker-loaderリポジトリを参照してください。

一般的なガイドライン

Workers APIを使用するときに最適な結果を得るには、以下のガイドラインに従ってください。

制限事項

ワーカーで処理を行う際には、留意すべきいくつかの制限があります。

デモプロジェクト

下記のプロジェクトは、Angular以外のNativeScriptプロジェクトおよびNativeScript Angularプロジェクトでマルチスレッド機能をどのように使用できるかを示しています。

NativeScript Angular Demo

入門

コアコンセプト

ユーザーインターフェース

ツール

ハードウェアアクセス

プラグインの開発

リリース

アプリテンプレート

パフォーマンスの最適化

フレームワークモジュール

ガイド

サポートを受ける

トラブルシューティング

Siedkick