Skip to main content
RSS feed Subscribe to feed

 

How to Create a Thread

This example describes a simple thread implementation.

Overview

Custom Workers are added by extending the CustomWorker and the CustomWorkerFactory classes. The WorkItem class is then usually extended to provide specific worker input and ouput. Optionally, a document node can be specified as worker model. The WorkerFactory will then override GetWorkerModelTriggerCore to specify a trigger on the properties used by the worker.

Background Information
  • Spotfire SDK\Examples\Extensions\SpotfireDeveloper.CustomWorkerExample
    The project contains a SimpleWorker demonstrating how to create and use a basic worker. It also contains the ChainedWorker demonstrating how to create and use a worker that delegates part of the work to another worker, in this case the SimpleWorker.

CustomWorker

public class SuffixWorker : CustomWorker<SuffixWorkerModel, SuffixWorkItem>
{
    public SuffixWorker()
    {
        // Empty
    }

    protected override void DoWorkCore(SuffixWorkerModel model, SuffixWorkItem workItem)
    {
        // Let us sleep a little to simulate complex work:
        Thread.Sleep(1000);

        // Calculate output:
        string result = workItem.Input + "::" + model.Suffix;

        // Submit the result:
        workItem.Result = result;
    }
}

CustomWorkerFactory

public class SuffixWorkerFactory : CustomWorkerFactory<SuffixWorker, SuffixWorkerModel>
{
    protected override SuffixWorker CreateCore()
    {
        return new SuffixWorker();
    }

    protected override Trigger GetWorkerModelTriggerCore(SuffixWorkerModel workerModel)
    {
        return Trigger.CreatePropertyTrigger(workerModel,
			 SuffixWorkerModel.PropertyNames.Suffix);
    }
}

WorkItem

public class SuffixWorkItem : WorkItem
{
    public SuffixWorkItem(string input) { … }

    public string Input { get; }

    public string Result { get; set; }
}

WorkerModel

[Serializable]
[PersistenceVersion(1, 0)]
public class SuffixWorkerModel : DocumentNode
{
    public new abstract class PropertyNames : CustomNode.PropertyNames
    {
        public static readonly PropertyName Suffix …
	}

    public string Suffix
    {
		...
    }

	...
}

Client usage

private WorkDispatcher<SuffixWorkItem> dispatcher;

public void UseWorker(SuffixWorkerModel model)
{
    model.Context.GetService<WorkManager>().CreateDispatcher(
        new SuffixWorkerFactory(),
        this.model, out this.dispatcher);

    model.Suffix = "World";
    SuffixWorkItem item = new SuffixWorkItem("Hello");
    item.PushResultHandler<SuffixWorkItem>(ResultHandler);
    this.dispatcher.AddFirst(item);
}

private void ResultHandler(SuffixWorkItem item)
{
    // This is executed on the worker thread...
    string result = item.Result;
    item.ReturnItem();
}