SL调用WCF方法,默认是异步的,但有些情况,我们使用同步会来的方便些,下面的文章提供了一种方式。
http://www.codeproject.com/KB/silverlight/SynchronousSilverlight.aspx
上述提供的方式是基于服务端WCF服务接口实现,可是有时不需要WCF服务接口,下面对此进行补充:
WCF服务如下:
namespace DanielVaughan.Silverlight.Examples.Web
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SimpleService //: ISimpleService
{
//static int connectionCount;
[OperationContract]
public string GetGreeting(string name)
{
Thread.Sleep(2000);
return "Hi " + name;
}
[OperationContract]
public List<string> GetDataList()
{
List<string> dataList = new List<string>();
Random r = new Random(DateTime.Now.Millisecond);
int max = r.Next(100);
for (int i = 0; i <max ; i++)
{
Thread.Sleep(100);
dataList.Add(i.ToString());
}
return dataList;
}
//public string InitiateConnection(string arbitraryIdentifier)
//{
// return (++connectionCount).ToString();
//}
}
}
客户端:
private void btnGetDataSynch_Click(object sender, RoutedEventArgs e)
{
this.lbData.ItemsSource = null;
ThreadPool.QueueUserWorkItem(delegate
{
DisplayMessage("同步获取数据中...");
var ws = ChannelManager.Instance.GetChannel<SimpleService>();
try
{
ObservableCollection<string> dataList = SynchronousChannelBroker.PerformAction<ObservableCollection<string>>(ws.BeginGetDataList, ws.EndGetDataList);
//if (Dispatcher.CheckAccess())
//{
// this.lbData.ItemsSource = dataList;
//}
//else
//{
// Dispatcher.BeginInvoke(delegate
// {
// this.lbData.ItemsSource = dataList;
// });
//}
DisplayData(this.lbData, dataList);
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
DisplayMessage("同步获取数据完成");
});
}
void DisplayMessage(string message)
{
DisplayText(this.tbMsg, message);
}
void DisplayText(TextBlock textBlock, string message)
{
if (Dispatcher.CheckAccess())
{
textBlock.Text = message;
}
else
{
Dispatcher.BeginInvoke(delegate
{
textBlock.Text = message;
});
}
}
void DisplayData(ListBox listBox, ObservableCollection<string> dataList)
{
if (Dispatcher.CheckAccess())
{
listBox.ItemsSource = dataList;
}
else
{
Dispatcher.BeginInvoke(delegate
{
listBox.ItemsSource = dataList;
});
}
}
本文介绍了一种在Silverlight应用中实现WCF服务同步调用的方法,并提供了客户端和服务端的具体实现代码示例。
434

被折叠的 条评论
为什么被折叠?



