From theory to practice (8): event broadcast
Three message exchange modes in WCF are discussed in the previous section: one-way, request/reply, and duplex. The first two items are relatively simple, and there is no need to talk about them. duplex is relatively complicated. The preceding section only implements simple callback. in actual application, there are many points worth noting, in this article, we will talk about the specific application of duplex and what deserves our attention.
Starting point of this article
By reading this article, you can understand the following knowledge:
- How to Implement Duplex-based event broadcast
- Resolve several issues in Duplex event broadcast
- Preliminary Discussion about Asynchronization
This article is suitable for readers
This article is moderateArticle, Requires a WCF message exchange and Windows ApplicationProgramDevelopment-related basics for WCF message exchange, please read the http://www.cnblogs.com/jillzhang/archive/2008/02/17/1071521.html
How to Implement Duplex-based event broadcast
Before discussing how to implement it, let's take a look at the functions to be implemented in this example? The example in this article implements a simple distributed task management system. Simply put, it executes a task on the server point and presents the task information to the client. It has the following features:
- By calling the accept () of the server, the client can connect to the server and maintain the session.
- When the client starts, it can remotely call getjobs () to obtain all the tasks on the current server, and present these tasks in the client form using List controls.
- The client can add a task to the server by calling addjob (). After the server completes the add operation, it will trigger the Add event andAllClient to broadcast this event
- When the client server sends a new task event broadcast, the client adds the new task to the List Control for display.
- The client can command the server to execute a specific task. After the task is executed and completed, the server broadcasts the task execution status as all clients, and broadcasts the task execution and event broadcast asynchronous execution.
- After receiving the broadcast, the client can update the task information.
Different from previous articles, this article first provides the final implementation results
To learn how to design and implement this example, you can download the following file for analysis:
Example:/files/jillzhang/jillzhang.event.rar
Here, I will only list projects in the example.
Project name |
Project Description |
jillzhang. event. core |
this project is used to define the WCF contract, it mainly includes iServer service contract, icallback service contract for callback, and job data contract |
jillzhang. event. service |
server implementation, server implements a service contract with broadcast event capabilities |
jillzhang. event. host |
service host program, one leleapplication |
jillzhang. event. client |
client implementation, used to consume the server. |
Jillzhang. event. Client2 |
And jillzhang. event. Client are an implementation, but to verify broadcast, you can consume the server together with jillzhang. event. Client. |
Resolve several issues in Duplex event broadcast
1) duplex mode requirements for service behavior concurrencymode
We know that concurrencymode controls service concurrency. By defaultThe value of concurrendmode is single, which sets the service to run in a single thread. When a request is not completed, the Service does not accept the next request. During callback, if the callback method is not set to one-way switch mode, the server will wait for the client to respond to the callback. This is not a good thing, the server does not guarantee that the client can normally execute the callback and return data. In more cases, we expect that the callback can be returned immediately after it is sent. There are two methods: a) set the callback method to one-way switching mode B) use multithreading. After my tests, when the callback method is set to the one-way modeSetting concurrencymode to single enables duplex bidirectional communication. The second method is also very simple. You only need to set concurrencymode to mutiple. In this case, even if the callback method is not one-way mode, duplex can be completed. It is worth noting that concurrencymode has a neutral attribute: concurrencymode. reentrant: In my heart, I don't like this guy. He can accept multiple requests in a single thread at the same time, but it has advantages and disadvantages. This guy cannot guarantee the integrity of the Request transaction, exercise caution when using the SDK.
2) Why can I broadcast instancecontextmode = instancecontextmode. persession?
If you set instancecontextmode to persession, we know that the server object is for each session, that is, each session will generate an object instance, so that if you want to implement broadcast, we must record the session information contained in the current service with a list object. During broadcast, we traverse the session List and perform one-by-one callback. This example cleverly utilizes the features that an event can include multiple delegated instances. A static event object can create a delegated instance for each session to fulfill the preceding requirements. You can compile the callback Traversal method as follows:
Private Void
Broadcastevent (callbackeventarg E, servereventhanlder temp)
{
If(Onstatuschanged! = Null
)
{
Foreach(Servereventhanlder HandlerIn
temp. getinvocationlist ()
{
Handler. begininvoke (This, E,NewAsynccallback (endasync ),Null
);
}
}
}
3) problems that have plagued me for a long time
In the previous article, I had a preliminary understanding of duplex. I thought the implementation of the example in this article would be smooth. However, I had a problem for a long time, the callback process is very unstable. Sometimes the callback process can be performed for 4.5 times. Sometimes, after 1 or 2 times, the callback process does not respond, and you may not be able to solve the problem because the callback process can be successful several times, why is it unstable? After some attempts, the problem could not be solved, and the callback did not respond. It must have been because the client and the server have lost the connection. When the session expires, communication between the two parties is interrupted. After analysis, my system is like this.
Will the session expire before the do () method after accept? After verification, it is indeed the problem here. The solution is to implement session maintenance by setting isterminating of the operation contract. When isterminating of an operation contract is set to false, this operation will not cause session interruption. The iServer is designed as follows to solve my problem:
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using System. servicemodel;
Namespace Jillzhang. event. Core
{
[Servicecontract (sessionmode = Sessionmode. required, callbackcontract = Typeof (Icallback)]
Public Interface IServer
{
[Operationcontract (isoneway = True , Isinitiating = True , Isterminating = False )]
Void Accept ();
[Operationcontract (isoneway = True , Isinitiating = False , Isterminating = False )]
Void Do ( String Jobname );
[Operationcontract (isoneway = True , Isinitiating = False , Isterminating = False )]
Void Addjob (job );
[Operationcontract (isoneway = False , Isinitiating = False , Isterminating = False )]
List < Job > Getjobs ();
}
}
Preliminary Discussion about Asynchronization
Inter-process communication is a very time-consuming task. If synchronous execution causes thread blocking,If it is on the server, it will reduce the service processing capability (this statement may have some problems, I will further verify, it is estimated to be retained, the advantage of multithreading on the server is that it provides the ability to process a single request in multiple threads, so as to prevent new requests from being accepted before a request is completed)If it is on the client, it will bring a poor user experience. Next we will discuss how to implement The Asynchronization between the server and the client.
On the server side, asynchronous events can be implemented through the begininvoke and endinvoke of Delegate. For details, refer to the implementation of the broadcastevent method of the Server Object method in the sample project jillzhang. event. Service.
On the client side, we can start multiple threads. Of course, the most convenient and quick way is to use backgroundworker background threads to process time-consuming operations. For details, see jillzhang. event. implement form1.cs in the client project.
References in this article
- Http://www.cnblogs.com/wayfarer/archive/2007/03/08/667865.html
- Http://www.cnblogs.com/caishiqi/archive/2007/10/05/914671.html
- Http://msdn.microsoft.com/msdnmag/issues/06/10/wcfessentials/default.aspx
Examples in this article
Example:/files/jillzhang/jillzhang.event.rar
Original exampleCodeIn, the binding used is nettcpbinding. A friend asked if wsdualhttpbinding encountered an exception. An example is also provided.
/Files/jillzhang/jillzhang.event_wsdualhttpbinding.rar