i run user defined scripts in wpf application using cs-script library. how can cancel script if runs endless? users write script can't rely on cancel flag checked inside script.
here simplified code snippet showing problem:
public partial class mainwindow : window { public string messagefromscript { { return (string)getvalue(messagefromscriptproperty); } set { setvalue(messagefromscriptproperty, value); } } public static readonly dependencyproperty messagefromscriptproperty = dependencyproperty.register("messagefromscript", typeof(string), typeof(mainwindow), new propertymetadata(null)); public mainwindow() { initializecomponent(); datacontext = this; } backgroundworker worker = null; private void onstart(object sender, routedeventargs e) { if(worker != null) { return; } worker = new backgroundworker(); worker.dowork += runscript; worker.runworkercompleted += scriptcompleted; worker.workersupportscancellation = true; worker.runworkerasync(); } private void scriptcompleted(object sender, runworkercompletedeventargs e) { if(e.cancelled) messagefromscript = "script cancelled"; else messagefromscript = e.result.tostring(); } private void runscript(object sender, doworkeventargs e) { dynamic script = csscript.evaluator.loadcode(@"using system; using system.threading; public class script { public string test() { {int count=0; while(true) { count++; console.writeline(count.tostring()); thread.sleep(200); }} return ""message script""; } }"); e.result = script.test(); } private void onstop(object sender, routedeventargs e) { if(worker == null) { return; } //todo: how stop script here? worker = null; } }
in test() method add parameter pass cancellationtoken script. design loops in script check canellation token if abort has been requested , break out. stop script call cancel() method of cancellationtokensource token passed script on invocation.
Comments
Post a Comment