基于AutoResetEvent的同步实现
利用AutoResetEvent的线程等待特性,可以折中实现Silverlight同步调用远端WCF服务。其原理就是在Silverlight发起异步调用远端WCF的时候进行线程阻塞,比记录异步调用远端WCF服务接口的完成事件,当异步调用完成后就终止线程阻塞,从而获取状态事件对象中或得调用远程接口所返回的结果。由于视图模型对象实现了INotifyPropertyChanged接口能够及时的更新界面元素,以此间接的就实现了同步方式调用。
public class AsyncCallStatus<T> { public AsyncCallStatus() { } public T CompletedEventArgs { get; set; } } public class BookFacade { private AutoResetEvent autoResetEvent = new AutoResetEvent(false); public void GetBook(BookViewModel viewModel) { if (viewModel == null) { throw new ArgumentNullException("viewModel", "参数不能为空。"); } DataService.DataServiceClient client = new DataService.DataServiceClient(); client.GetBookCompleted += client_GetBookCompleted; var status = new AsyncCallStatus<GetBookCompletedEventArgs>(); client.GetBookAsync(status); //阻塞线程 autoResetEvent.WaitOne(); if (status.CompletedEventArgs.Error != null) { throw status.CompletedEventArgs.Error; } var book = status.CompletedEventArgs.Result; viewModel.ID = book.ID; viewModel.Name = book.Name; viewModel.Author = book.Author; viewModel.Price = book.Price; } private void client_GetBookCompleted(object sender, GetBookCompletedEventArgs e) { var status = e.UserState as AsyncCallStatus<GetBookCompletedEventArgs>; status.CompletedEventArgs = e; //终止线程阻塞 autoResetEvent.Set(); } }