询问者
WPF客户端调用WCF时,能否统一拦截所有方法来做进度展示?

问题
-
在WPF客户端中,我每次调用WCF服务都是这样调用的:
// 全局的IMyWcfClient private IMyWcfClient _service = new MyWcfClient();
// 某个方法中 try { // 显示进度条 BusyIndicator.IsOpen = true; var data = await _service.GetDataAsync(); } finally { // 关闭进度条 BusyIndicator.IsOpen = false; }
我想能不能这样:
// 全局的IMyWcfClient private IMyWcfClient _service = new MyWcfClient();
// 在页面的Loaded事件里注册事件处理 _service.BeforeOperation += (s, e) => {BusyIndicator.IsOpen = true;} _service.AfterOperation += (s, e) => {BusyIndicator.IsOpen = false;}
// 某个方法中 var data = await _service.GetDataAsync();
我该怎么实现??或者说,还有其他更好的实现??
- 已编辑 jesse hao 2019年4月23日 8:42
- 已移动 Cherry BuMicrosoft contingent staff 2019年4月24日 5:13 relate issue
全部回复
-
Hi jesse hao,
根据你的描述, 我觉得你的问题是有关wcf的,所以我把你的这个case移到wcf相关的论坛, 这将会有更加专业的人员来帮助你解决你的问题。
https://social.msdn.microsoft.com/Forums/zh-CN/home?forum=wcfzhchs&filter=alltypes&sort=lastpostdesc
Best Regards,
Cherry
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com. -
Hi Jesse hao,
现在显示进度的通用解决方案是使用IProgress接口,在C#5中有个IProgress<T>接口, 它有个report方法,可以报告当前任务处理的进度,我们需要在服务端耗时任务中报告进度。然后在客户端使用Progress<T>实现类,它接受一个Action<T>委托,可以利用这个委托显示进度条进度。
服务端
public async void DoProcessingAsync(IProgress<int> progress) { for (int i = 0; i != 100; ++i) { Thread.Sleep(100); if (progress != null) { progress.Report(i); } } }
调用
private async void button1_Click(object sender, EventArgs e) { var progress = new Progress<int>(x => label1.Text = x + "%"); await Task.Run(() => DoProcessingAsync(progress)); this.label1.Text = "Completed"; }
https://docs.microsoft.com/zh-cn/dotnet/api/system.progress-1?view=netframework-4.8
https://devblogs.microsoft.com/dotnet/async-in-4-5-enabling-progress-and-cancellation-in-async-apis/
你也可以考虑使用WCF双工通信,参考我之前我写过的列子。
https://social.msdn.microsoft.com/Forums/vstudio/en-US/c55c8ad5-36a7-4101-876c-8cfd1cc713db/how-to-write-a-console-mode-client-for-duplex-binding?forum=wcf
Best Regards
Abraham
- 已编辑 Abraham QianMicrosoft contingent staff 2019年4月25日 9:53