Skip to content
CheshireCaat edited this page Feb 23, 2020 · 15 revisions

Run functions with client

If you want to run the function, and you do not need to control the lifetime of the threads, use BasRemoteClient instance for this. In this case, the client itself creates and terminates BAS threads to perform functions.

The RunFunction() method returns an object that implements the IBasFunction interface. Using it, you can stop the execution of a running function, get the ID of the thread in which it was run, or get the function result using methods GetTask() or GetTask<TResult>().

GetTask() returns a task object whose result type is not defined in advance, so by default it is dynamic. If you want to convert the result to a specific type, use GetTask<TResult>().

Take a look at the examples:

Single function call

using (var client = new BasRemoteClient(new Options {ScriptName = "TestRemoteControl"}))
{
    await client.Start();

    // Call one function and get the result.
    // Type of result is dynamic here.
    var result = await client.RunFunction("GoogleSearch", new Params
    {
        {"Query", "cats"}
    }).GetTask();
    
    Console.ReadKey();
}

Parallel function call

var task1 = client.RunFunction("GoogleSearch", new Params {{"Query", "cats"}}).GetTask();
var task2 = client.RunFunction("GoogleSearch", new Params {{"Query", "dogs"}}).GetTask();
var result = await Task.WhenAll(task1, task2);

// Type of result is dynamic[] here.
foreach (var taskResult in result)
foreach (var link in taskResult)
    Console.WriteLine(link);

Handle errors

You can also wrap your function call to try/catch block in order to handle possible errors that may be returned by function. All function errors represents by FunctionException class, that contains custom error message returned by your script.

try
{
    var result = await client.RunFunction("NotExistingFunction", Params.Empty).GetTask();
}
catch (FunctionException ex)
{
    Console.WriteLine(ex.Message);
}

Function interruption

RunFunction returns interface IBasFunction that contains Stop() method. By calling this method you can imeddiately stops function execution. It can be useful if you want to add timeouts to call your function or you don't want to wait for it to complete.

In the example below, a function is called that takes a very long time, but we stop it after three seconds of waiting.

var function = client.RunFunction("LongRunningFunction", Params.Empty);

await Task.Delay(5000);
function.Stop();