Use local services to asynchronously execute custom activity business logic

Source: Internet
Author: User

Generally, the business logic of the custom activity we develop is written in the execte method. Because a workflow instance is executed on a single thread, when the workflow is executing this activity, this activity exclusively occupies the thread of the entire workflow. If the custom activity requires a long time to complete tasks, other requests in the workflow cannot be processed. Therefore, we do not recommend that you put all the business logic in the execute Method for execution.

1. we can put the business logic of the activity into the local service for asynchronous execution. The following example shows how to create an ordered workflow console project, first, we first write two classes of carywork and caryworkresult, which respectively represent the work items we want to execute and the returned results. The Code is as follows:

[Serializable]public class CaryWork{    public Guid InstanceId { get; set; }    public String WorkItem { get; set; }    public String ResultQueueName { get; set; }    public CaryWork( Guid InstanceId, String ResultQueueName, String WorkItem)    {        this.InstanceId = InstanceId;        this.ResultQueueName = ResultQueueName;        this.WorkItem = WorkItem;    }
}
[Serializable]public class CaryWorkResult{   public String Result { get; set; }
public CaryWorkResult(String Result) { this.Result = Result; }}

Resultqueuename indicates the queue name of the returned result.
Instanceid indicates the workflow ID.
Workitem indicates the task to be executed


2. Then we start to compile the local service. First, we declare an interface. The method in the interface will be called in the Custom activity. The Code is as follows:
Public interface ilongtaskservices
{
Voiddolongtaskwork (caryworkworktodo );
}

The code for implementing this interface is as follows:

Public class longtaskservices: workflowruntimeservice, ilongtaskservices {private random _ random = new random (); Public void dolongtaskwork (carywork worktodo) {threadpool. queueuserworkitem (tpworkcallback, worktodo); console. writeline ("work item queue: {0}", worktodo. workitem);} private void tpworkcallback (object state) {carywork workitem = state as carywork; workflowinstance instance = runtime. getworkflow (workitem. instanceid); int32 MSW = _ random. next (1000,500 0); thread. sleep (MSW); caryworkresult response = new caryworkresult (string. format (
"Work Item-{0} returned-{1}", workitem. workitem, MSW); instance. enqueueitem (workitem. resultqueuename, response, null, null );}}
In the local service, we use the thread pool to execute the tasks we want to complete. We use the thread sleep method to assume that each task will be executed for a long time.
The caryworkresult object is returned.
 
3. Now we implement our custom activities with the following code:
Public partial class longtaskactivity: Activity, iactivityeventlistener <queueeventargs> {
Public static dependencyproperty workitemproperty = dependencyproperty. register ("workitem", typeof (string), typeof (longtaskactivity); [descriptionattribute ("workitem")] [browsableattribute (true)] [designerserializationvisibilityattribute (designerserializationvisibility. visible)] Public String workitem {get {return (string) (base. getvalue (longtaskactivity. workitemproperty);} set {base. setvalue (longtaskactivity. workitemproperty, value) ;}} private string queuename = guid. newguid (). tostring (); Public longtaskactivity () {initializecomponent ();} protected override activityexecutionstatus execute (activityexecutioncontext executioncontext) {ilongtaskservices longrunningservice = executioncontext. getservice (typeof
(Ilongtaskservices) as ilongtaskservices; workflowqueuingservice queueservice = executioncontext. getservice (typeof
(Workflowqueuingservice) as workflowqueuingservice;
Workflowqueue queue = queueservice. createworkflowqueue (queuename, true); queue. registerforqueueitemavailable (this); carywork request = new carywork (this. workflowinstanceid, queuename, workitem); console. writeline ("calling local service: {0}", workitem); longrunningservice. dolongtaskwork (request); Return activityexecutionstatus. executing;} public void onevent (Object sender, queueeventargs e) {activityexecutionco Ntext AEC = sender as activityexecutioncontext; workflowqueuingservice queueservice = AEC. getservice <workflowqueuingservice> (); workflowqueue queue = queue. getworkflowqueue (E. queuename); If! = NULL & queue. Count> 0) {caryworkresult response = queue. dequeue () as caryworkresult; If (response! = NULL) console. writeline ("Result: {0}", response. Result);} queueservice. deleteworkflowqueue (E. queuename); AEC. closeactivity ();}
}
In a custom activity, we call the method of the local service to execute work items. The queue workflow queue is created and the execution method returns
Activityexecutionstatus. Executing indicates that the work item is not completed. After completion, the result is output to the console in the onevent event and
Use the closeactivity method of AEC to disable the activity.
 
4. Design a workflow. Drag a parallelactivity activity in the workflow designer and drag a custom activity to each branch,
And set its workitem attribute,
 
 
5. In the Host Program, we need to load the local service to the workflow engine. The Code is as follows:
Static void main (string [] ARGs) {using (workflowruntime = new workflowruntime () {autoresetevent waithandle = new autoresetevent (false); workflowruntime. workflowcompleted + = delegate (Object sender, workflowcompletedeventargs E)
{Waithandle. set () ;}; workflowruntime. workflowterminated + = delegate (Object sender, workflowterminatedeventargs e) {console. writeline (E. exception. message); waithandle. set () ;}; workflowruntime. addservice (New longtaskservices (); workflowinstance instance = workflowruntime. createworkflow (typeof
(Carylongwf. longtaskworkflow); console. writeline ("--- workflow execution start ---"); instance. start (); waithandle. waitone (); console. writeline ("--- workflow execution ends ---");}}
 
6. The execution result of the running program is as follows:

 

From the results, we sometimes see that the order of workitem1 and workitem2 is reversed, because we performed random sleep actions in the local service.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.