我有以下情况:
Client who is requesting a webservice to start
public bool Start(MyProject project, string error)
A web service who receives the call from the client in a method
public event EventHandler<StartEventArgs> startEvent; public bool Start(MyProject project, string error) { Task<bool> result = StartAsync(project, error); return result.Result; } protected virtual void OnStart(StartEventArgs e) { // thread safe trick, snapshot of event var se = startEvent; if (se != null) { startEvent(this, e); } } private Task<bool> StartAsync(MyProject project, string error) { var taskCompletion = new TaskCompletionSource<bool>(); this.startEvent += (p, e) => taskCompletion.TrySetResult((e.Error == string.Empty) ? true : false); this.OnStart(new StartEventArgs(project, error)); return taskCompletion.Task; }
An application that is subscribing to an event that is located in the web service:
app.Start += EventHandler(App_Start) private bool App_Start() { // does something returns true/false }
I want the web service to fire off the event in a Task, then wait for the function in the app.exe to finish and then return here to notify the user that the task has completed successfully.
Task<bool> startTask = Task.Factory.StartNew(() => { OnStart() });
startTask.WaitAll(); // I think this is what I would need to for 4.0
return startTask.Result
我希望我的描述足够清晰,让人们能够理解我的意图。我希望服务不需要了解客户端的任何信息,只需运行任务,一旦事件完成执行,就返回到这个点,并向客户端返回代表成功/失败的布尔值。
这种方式可行吗?还是我采取了错误的方法?
更新: 显然OnStart不是一个事件,那么我该如何实现你所说的内容?