[英]WCF callback not working as expected
我做了一個WCF服務,該服務向WPF客戶端進行了回調。 我只是在WPF客戶端的文本框中顯示進度。 我首先得到的是跨線程操作無效。 然后,我修改了客戶端代碼,並使用了諸如Invoke()
和BeginInvoke()
。 現在,客戶端代碼僅顯示值100%。 實際上,它應該顯示0-100%的值。 有什么辦法嗎?
wcf服務中的代碼:
namespace ReportService
{
[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Reentrant,InstanceContextMode=InstanceContextMode.Single)]
public class Report : IReportService
{
public void ProcessReport()
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(1000);
OperationContext.Current.GetCallbackChannel<IReportCallback>().ReportProgress(i);
}
}
}
}
客戶端代碼:
namespace Report
{
[CallbackBehavior(UseSynchronizationContext=false)]
public partial class Form1 : Form,ReportService.IReportServiceCallback
{
delegate void delSetTxt(int percentCompleted);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
InstanceContext ic= new InstanceContext(this);
ReportService.ReportServiceClient client = new ReportService.ReportServiceClient(ic);
client.ProcessReport();
}
public void ReportProgress(int percentCompleted)
{
// this.Invoke(new Action(() => { this.textBox1.Text = percentCompleted.ToString(); }));
Thread t = new Thread(() => setTxt(percentCompleted));
t.Start();
}
public void setTxt(int percentCompleted)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new delSetTxt(setTxt), new object[] { percentCompleted });
return;
}
this.textBox1.Text = percentCompleted.ToString() + " % complete";
}
}
}
對該服務進行調用時,GUI線程停留在button_click方法中。 因此,GUI線程不得凍結。
有(至少)兩個有效的解決方案,我對其進行了測試:
將[OperationContract(IsOneWay = true)]
放在服務器和回調操作上
將[OperationContract(IsOneWay = true)]
放在回調操作上,不要用await/async
鎖定GUI線程:
private async void button1_Click(object sender, EventArgs e) { InstanceContext ic = new InstanceContext(this); ReportServiceClient client = new ReportServiceClient(ic); await client.ProcessReportAsync(); //client.ProcessReport(); }
祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.