PDA

View Full Version : cho em hỏi về 2 hàm này trong WCFService



hollow_xy
28-11-2010, 12:19
Em có 1 ứng dụng Silverlight, trong đó có đoạn code như sau:

void Page_Loaded(object sender, RoutedEventArgs e)
{
StartingHandServiceClient service = new
StartingHandServiceClient();
service.GetHandsCompleted += new
EventHandler<GetHandsCompletedEventArgs>
(service_GetHandsCompleted);

service.GetHandsAsync();
}

void service_GetHandsCompleted(object sender, GetHandsCompletedEventArgs e)
{
this.grdData.ItemsSource = e.Result;
}



Cho em hỏi chức năng và hoạt động của các hàm StartingHandServiceClient(), và hàm
service.GetHandsCompleted += new EventHandler<GetHandsCompletedEventArgs>
(service_GetHandsCompleted);
và:service.GetHandsAsync();
Tại sao lại gọi hàm service.GetHandsAsync sau cùng ạ, em tham khảo tài liệu nhưng không thấy tài liệu nói rõ ràng về các hàm này
Em cảm ơn.

littleNeo
28-11-2010, 15:42
StartingHandServiceClient là client (service proxy) được generate cho StartingHandService từ Svcutil, StartingHandServiceClient() chỉ là constructor để tạo ra service client, còn bên trong nó làm gì thì ko cần quan tâm lắm đâu.

Do service client được generate với /async (Generate Asynchronous Operations trong Advanced option khi Add Service Reference) nên bạn sẽ có các hàm dạng <MethodName>Async và các event <MethodName>Completed nhằm phục vụ cho Asynchronous Programming phía client thôi, ko có gì đặc biệt đâu. Ở đây service có 1 hàm tên là GetHands, khi generate với option /async thì sẽ có GetHandsCompleted event và method GetHandsAsync.

Lý do tại sao gọi hàm GetHandsAsync sau cùng, hay tất cả những chi tiết liên quan nói trên, cùng những thứ liên quan chưa nói đến thì mời bạn nghiên cứu Asynchronous Programming của .NET.

Cái nữa là bạn nên viết như thế này:


using(StartingHandServiceClient client = new StartingHandServiceClient())
{
// Do your stuff
}


hoặc



StartingHandServiceClient client = null;
try
{
...
client.Close();
}
catch (CommunicationException e)
{
...
client.Abort();
}
catch (TimeoutException e)
{
...
client.Abort();
}
catch (Exception e)
{
...
client.Abort();
throw;
}


Mục đích là để đóng service channel lại khi không dùng nữa để đóng session lại, cứ mỗi lần new bạn lại tạo ra 1 session mới, gọi 10 lần ra 10 session và lần gọi thứ 11 sẽ bị block nếu server chỉ có thể chịu limit 10 session. Microsoft khuyến cáo nên dùng try catch finally hơn là dùng using, vì trong 1 số trường hợp using sẽ gây ra lỗi, bài viết ở đây http://msdn.microsoft.com/en-us/library/aa355056.aspx .

hollow_xy
28-11-2010, 21:33
Cảm ơn rất nhiều, bài biết rất bổ ích, Thanks