标签:
这篇东西原写在csdn.net上,最近新开通了博客想把零散在各处的都转移到一处。
一、源起 学WCF有一段时间了,可是无论是微软的WebCast还是其他网上的教程,亦或我购买的几本书中,都没有怎么提到服务器端事件的订阅。(后来购买的一本WCF服务编程中提供了关于订阅和发布的例子) 网上也查了很多,但大部分都没有清楚地讲到这部分内容,有的虽然是讲这部分内容,但也是语焉不详。最重要的部分都没有讲到(也许是因为水平太差,看不懂)。而且网上和书上所用的语言都是C#,这让人很恼火,虽然我能使用C#,但总是不如用了十几年的VB看起来顺眼。而且最关键的是C#关于委托和事件处理上和VB有着很大的不同。比如:在C#中,事件本质上就是委托,而且处理方式都一样。但在VB中事件和委托很多差别,尤其是在处理方式上。比如,VB中事件不能直接支持返回列表,虽然编译器提供了一个变形后的变量来提供支持,但和c#中的直接遍历还是差很多。所以在把C#代码转换成VB代码时,一遇到事件或委托就很难办,因为用的方法不同。直接把代码语法改掉是编译不过的。这让我着实忧闷了很久。因为写项目,一定会遇到订阅和发布的。 前几天在网上又搜索相关的文章,这次也许运气很好,找到了一篇讲事件广播的,是一个叫张玉彬的博客上的文章,文章名叫:
WCF从理论到实践(8):事件广播 ,文章地址:http://www.cnblogs.com/jillzhang/archive/2008/02/24/1079339.html 。当然一点也不意外,这篇文章里面用的代码是C#(搞什么?VB没人用了吗?),最可心的是文章提供了例子代码。没什么好说的,把代码当回来,打开直接在VS中用VB重写一遍。。。。。所以,就有了这篇日志。呵呵。这样,也算是对自己这段时间学习WCF的一个小总结。如果能帮上哪位学VB朋友的忙的话那就最好不过了。呵呵。
二、实例分析 1、这是一个微软培训教程中用过的一个例子。我记得在学习Remoting时学过这个项目。很简单的一个例子: 服务器上维护一个JOB List,客户端用来提交、执行JOB,服务器将JOB状态和结果通知给每个客户端。这样就必须实现客户端订阅服务端事件。看起来是这个样子的。其实,非网络的事件,我们知道是比较容易实现的。也就是自定义事件的问题。一直以来,我总以为客户端订阅服务器事件也象在单机程序中那样。但由于两端不在一个程序域内,所以无法实现事件在两端的传播。我曾试图把委托或事件做为数据契约(DataContract)来处理,结果大家都知道。委托根本就无法传递和准确序列化,而事件根本就不支持数据契约(后来在书看到,事件必须添加FiledData特性才能支持契约,而委托虽然支持契约,却无法实现正确序列化)。不废话了。 2、原文章部分 略。(运行部分截图也见上文提到 的文章,不管是不是原创,毕竟对我有很多帮助,就不抢别人功劳了。呵呵。) 三、我的代码 由于这个例子相当简单,再加上本人也没什么写文章的天赋,所以,话就不多说了。直接上代码。。。。 1、使用事件进行广播 1)项目用到的JOB类:
- <DataContract()>
- Public Class job
- Private m_Name As String
- Private m_Status As String
- Private m_LastRunTime As DateTime
- Private m_LastRunResult As String
-
- Public Sub New()
- Me.Status = "Sleeping"
- Me.LastRunResult = ""
- End Sub
-
- <DataMember()>
- Public Property Name As String
- Get
- Return m_Name
- End Get
- Set(ByVal value As String)
- m_Name = value
- End Set
- End Property
-
- <DataMember()>
- Public Property Status As String
- Get
- Return m_Status
- End Get
- Set(ByVal value As String)
- m_Status = value
- End Set
- End Property
-
- <DataMember()>
- Public Property LastRunTime As DateTime
- Get
- Return m_LastRunTime
- End Get
- Set(ByVal value As DateTime)
- m_LastRunTime = value
- End Set
- End Property
-
- <DataMember()>
- Public Property LastRunResult As String
- Get
- Return m_LastRunResult
- End Get
- Set(ByVal value As String)
- m_LastRunResult = value
- End Set
- End Property
- End Class
2)项目中用到的回调接口
- <ServiceContract()>
- Public Interface ICallback
- <OperationContract(IsOneWay:=True)>
- Sub StatusChanged(ByVal job As job)
-
- <OperationContract(IsOneWay:=True)>
- Sub OnAdd(ByVal newJob As job)
-
-
- End Interface
3)项目中用到的服务契约
- <ServiceContract(CallbackContract:=GetType(ICallback))>
- Public Interface IService
-
-
-
-
-
-
-
-
-
-
- <OperationContract(IsOneWay:=True, IsInitiating:=True, IsTerminating:=False)>
- Sub Accept()
-
- <OperationContract(IsOneWay:=True, IsInitiating:=True, IsTerminating:=False)>
- Sub DoJob(ByVal jobName As String)
-
- <OperationContract(IsOneWay:=True, IsInitiating:=True, IsTerminating:=False)>
- Sub AddJob(ByVal newJob As job)
-
- <OperationContract(IsOneWay:=False, IsInitiating:=True, IsTerminating:=False)>
- Function GetJobs() As List(Of job)
-
-
- End Interface
说明:按照 网上文章的说法,事件广播要使用到 会话。但实际上,会话在这里并不重要。这我在后面验证。 4)项目中的服务实现类 这里,要用到InstanceContextMode特性,因为项目在这时还要保持会话。
- <ServiceBehavior(InstanceContextMode:=InstanceContextMode.Single, ConcurrencyMode:=ConcurrencyMode.Multiple)>
- Public Class JobServerImplement
- Implements IService
-
- Public Shared m_jobs As List(Of job)
- Public Shared jobs_Lock As Object
-
- Public Delegate Sub JobServerEventHandler(ByVal sender As Object, ByVal e As JobCallbackEventArg)
-
-
- Public Shared onChangeEvents As List(Of JobServerEventHandler)
- Public Shared onAddEvents As List(Of JobServerEventHandler)
-
-
- Public Shared clientCallBackChannles As List(Of ICallback)
-
-
-
-
- Public Shared Custom Event onJobStatusChanged As JobServerEventHandler
- AddHandler(ByVal value As JobServerEventHandler)
- If jobs_Lock Is Nothing Then
- jobs_Lock = New Object()
- End If
- If onChangeEvents Is Nothing Then
- SyncLock jobs_Lock
- onChangeEvents = New List(Of JobServerEventHandler)
- End SyncLock
- End If
-
- SyncLock jobs_Lock
- onChangeEvents.Add(value)
- Console.WriteLine("AddHandler Done!")
- End SyncLock
- End AddHandler
-
- RemoveHandler(ByVal value As JobServerEventHandler)
- If onChangeEvents Is Nothing Then
- Return
- End If
- SyncLock jobs_Lock
- onChangeEvents.Remove(value)
- Console.WriteLine("RemoveHandler Done!")
- End SyncLock
- End RemoveHandler
-
- RaiseEvent(ByVal sender As Object, ByVal e As JobCallbackEventArg)
- For Each tmpH As JobServerEventHandler In onChangeEvents
- tmpH.BeginInvoke(sender, e, Nothing, Nothing)
-
- Console.WriteLine("RaiseEvent")
- Next
- End RaiseEvent
- End Event
-
-
-
-
-
-
-
-
-
-
-
-
- Dim callbackInterface As ICallback
-
-
- Private Sub CallBackOnce(ByVal theCallBack As ICallback, ByVal e As JobCallbackEventArg)
- Try
- If e.ChangeReason = "Add" Then
- Console.WriteLine("CallBackOnce reason: Add")
- theCallBack.OnAdd(e.Job)
- Else
- Console.WriteLine("CallBackOnce reason: Modi")
- theCallBack.StatusChanged(e.Job)
- End If
- Catch ex As Exception
- Console.WriteLine("CallBackOnce Got Error:" & ex.Message)
- End Try
- End Sub
-
-
- Private Sub Server_Delegate_StatusChanged(ByVal sender As Object, ByVal e As JobCallbackEventArg)
- Try
- If e Is Nothing Or e.Job Is Nothing Then
- Console.WriteLine("Server_Delegate_StatusChanged e Or e.Job is nothing.")
- Exit Sub
- Else
- Console.WriteLine("Server_Delegate_StatusChanged Begin!")
-
-
- For Each callOnce As ICallback In clientCallBackChannles
- CallBackOnce(callOnce, e)
-
-
-
-
-
-
-
- Next
-
- Console.WriteLine("Server_Delegate_StatusChanged Done!")
- End If
- Catch ex As Exception
- Console.WriteLine("Server_OnStatusChange Errors:" & ex.Message)
- End Try
- End Sub
-
-
- Private Sub Server_OnStatusChanged(ByVal sender As Object, ByVal e As JobCallbackEventArg)
- Try
- If e Is Nothing Or e.Job Is Nothing Then
- Console.WriteLine("Server_OnStatusChange e Or e.Job is nothing.")
- Exit Sub
- Else
- Console.WriteLine("Server_OnStatusChange Begin!")
-
- If e.ChangeReason = "Add" Then
- Console.WriteLine("server_onStatusChanged reason: Add")
-
- callbackInterface.OnAdd(e.Job)
- Else
- Console.WriteLine("server_onStatusChanged reason: Modi")
- callbackInterface.StatusChanged(e.Job)
- End If
-
- Console.WriteLine("Server_OnStatusChange Done!")
- End If
- Catch ex As Exception
- Console.WriteLine("Server_OnStatusChange Errors:" & ex.Message)
- End Try
- End Sub
-
-
- Private Sub EndAsync(ByVal ar As IAsyncResult)
-
- Dim dEndHandler As JobServerEventHandler = Nothing
-
- Console.WriteLine("EndAsync Begin!")
- Try
-
-
- Dim arRemote As System.Runtime.Remoting.Messaging.AsyncResult = CType(ar, System.Runtime.Remoting.Messaging.AsyncResult)
-
- dEndHandler = CType(arRemote.AsyncDelegate, JobServerEventHandler)
-
- dEndHandler.EndInvoke(ar)
- Console.WriteLine("EndAsync End!")
- Catch ex As Exception
-
- RemoveHandler onJobStatusChanged, dEndHandler
-
-
- Console.WriteLine("EndAsync Errors:" & ex.Message)
- End Try
- End Sub
-
-
- Private Sub BroadcastEvent(ByVal e As JobCallbackEventArg)
-
-
-
- Console.WriteLine("BroadcastEvent Begin!")
- Try
-
-
-
-
-
-
- Server_Delegate_StatusChanged(Me, e)
-
- Console.WriteLine("BroadcastEvent End!")
- Catch ex As Exception
- Console.WriteLine("BroadcastEvent Errors:" & ex.Message)
- End Try
-
- End Sub
-
- Public Sub Accept() Implements IService.Accept
- Console.WriteLine("Accept Begin!")
- Console.WriteLine("启动服务实例")
- Try
-
-
- callbackInterface = OperationContext.Current.GetCallbackChannel(Of ICallback)()
-
-
-
-
-
-
-
-
- AddDelegate(AddressOf Me.Server_Delegate_StatusChanged)
-
- AddCallBack(callbackInterface)
- Catch ex As Exception
- Console.WriteLine("Accept Errors: " & ex.Message)
- End Try
-
- Console.WriteLine("Accept End!")
- End Sub
-
- Private Sub AddCallBack(ByVal chl As ICallback)
- Console.WriteLine("AddCallBack Begin!")
- Try
- If jobs_Lock Is Nothing Then
- jobs_Lock = New Object()
- End If
- If clientCallBackChannles Is Nothing Then
- SyncLock jobs_Lock
- clientCallBackChannles = New List(Of ICallback)
- End SyncLock
- End If
-
- SyncLock jobs_Lock
- clientCallBackChannles.Add(chl)
- Console.WriteLine("AddCallBack Done!")
- End SyncLock
-
- Catch ex As Exception
- Console.WriteLine("AddCallBack Got Error:" & ex.Message)
- End Try
-
-
- End Sub
-
- Private Sub AddDelegate(ByVal theDelegate As JobServerEventHandler)
- Console.WriteLine("AddDelegate Begin!")
- Try
- If jobs_Lock Is Nothing Then
- jobs_Lock = New Object()
- End If
- If onChangeEvents Is Nothing Then
- SyncLock jobs_Lock
- onChangeEvents = New List(Of JobServerEventHandler)
- End SyncLock
- End If
-
- SyncLock jobs_Lock
- onChangeEvents.Add(theDelegate)
- Console.WriteLine("AddDelegate Done!")
- End SyncLock
- Catch ex As Exception
- Console.WriteLine("AddDelegate Got Error:" & ex.Message)
- End Try
-
- End Sub
-
- Public Sub AddJob(ByVal newJob As job) Implements IService.AddJob
- Console.WriteLine("AddJob")
- Try
- If jobs_Lock Is Nothing Then
- jobs_Lock = New Object()
- End If
- If m_jobs Is Nothing Then
- SyncLock jobs_Lock
- m_jobs = New List(Of job)
- End SyncLock
- End If
- For Each jobItem As job In m_jobs
- If newJob.Name = jobItem.Name Then
- Console.WriteLine("Job 已存在。")
- Return
- End If
- Next
-
-
- newJob.Status = "Sleeping"
- newJob.LastRunResult = "Created"
-
- SyncLock jobs_Lock
- m_jobs.Add(newJob)
- End SyncLock
-
- Console.WriteLine("AddJob 添加完毕。开始广播事件...")
-
- Dim e As JobCallbackEventArg = New JobCallbackEventArg()
- e.Job = newJob
- e.ChangeReason = "Add"
-
- BroadcastEvent(e)
-
-
-
- Console.WriteLine("AddJob 广播事件完毕。")
- Catch ex As Exception
- Console.WriteLine("AddJob Errors: " & ex.Message)
- End Try
-
- Console.WriteLine("AddJob End!")
- End Sub
-
-
- Private Function GetJobByname(ByVal theJobName As String) As job
- For Each jobItem As job In m_jobs
- If jobItem.Name = theJobName Then
- Return jobItem
- End If
- Next
-
- Return Nothing
- End Function
-
- Public Sub DoJob(ByVal jobName As String) Implements IService.DoJob
- Dim theJob As job = GetJobByname(jobName)
- Try
- Dim e As JobCallbackEventArg = New JobCallbackEventArg()
-
- If theJob.Status = "Finished" Then
- Return
- End If
-
- theJob.Status = "Running"
- theJob.LastRunResult = "Working"
- theJob.LastRunTime = DateTime.Now
- e.Job = theJob
-
-
- BroadcastEvent(e)
-
- Console.WriteLine("任务" + theJob.Name + "正在执行")
-
- System.Threading.Thread.Sleep(1000 * 10)
-
- e = New JobCallbackEventArg()
- theJob.Status = "Finished"
- theJob.LastRunTime = DateTime.Now
- theJob.LastRunResult = "Done!"
- e.Job = theJob
-
- BroadcastEvent(e)
-
- Catch ex As Exception
-
- theJob.Status = "Sleeping"
- theJob.LastRunResult = "Fail"
- End Try
- End Sub
-
- Public Function GetJobs() As System.Collections.Generic.List(Of job) Implements IService.GetJobs
-
- Console.WriteLine("GetJobs")
-
- Return m_jobs
- End Function
- End Class
-
- Public Class JobCallbackEventArg
- Inherits EventArgs
-
- Private m_CallbackJob As job
-
- Private m_ChangeReason As String
-
- Public Property Job As job
- Get
- Return m_CallbackJob
- End Get
- Set(ByVal value As job)
- m_CallbackJob = value
- End Set
- End Property
-
- Public Property ChangeReason As String
- Get
- Return m_ChangeReason
- End Get
- Set(ByVal value As String)
- m_ChangeReason = value
- End Set
- End Property
- End Class
5)承载服务代码
- Imports System.Runtime.Serialization
- Imports System.ServiceModel
- Module Module1
-
- Sub Main()
- Using host As ServiceHost = New ServiceHost(GetType(WcfJobService.JobServerImplement))
- host.Open()
-
- Console.WriteLine("Service Started!")
-
-
- Console.WriteLine("Press any key to Exit!")
- Console.ReadKey()
-
- host.Close()
- End Using
- End Sub
-
- End Module
承载服务配置 app.config 上文提到 的文章的例子中并没有关于Mex终结点,之所以在这里配置无数据终结点,是为了让客户端获取代理方便些。而且,在这里用的绑定是TCP,也就是说,这是个天然支持回调的协议。而且速度也很快,只是IIS6无法承载
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <system.diagnostics>
- <sources>
-
- <source name="DefaultSource" switchName="DefaultSwitch">
- <listeners>
- <add name="FileLog"/>
-
-
- </listeners>
- </source>
- </sources>
- <switches>
- <add name="DefaultSwitch" value="Information" />
- </switches>
- <sharedListeners>
- <add name="FileLog"
- type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
- initializeData="FileLogWriter"/>
-
-
- </sharedListeners>
- </system.diagnostics>
- <system.serviceModel>
- <services>
- <service name="WcfJobService.JobServerImplement" behaviorConfiguration ="MEX">
- <host>
- <baseAddresses>
-
- <add baseAddress ="http://localhost:8300/"/>
- </baseAddresses>
- </host>
-
- <!--<endpoint address="Event" binding="netTcpBinding"
- bindingConfiguration="DuplexBinding" contract="WcfJobService.IService" />-->
- <endpoint address="Event" binding="wsDualHttpBinding"
- bindingConfiguration="DuplexWsHttpBinding" contract="WcfJobService.IService" />
-
- <endpoint address ="http://localhost:8080/MEX" binding ="mexHttpBinding" contract ="IMetadataExchange" />
- </service>
- </services>
- <bindings>
- <wsDualHttpBinding>
- <binding name="DuplexWsHttpBinding" sendTimeout ="00:00:05"></binding>
- </wsDualHttpBinding>
- <netTcpBinding>
- <binding name ="DuplexBinding" sendTimeout ="00:00:03" ></binding>
- </netTcpBinding>
- <wsHttpBinding>
- <binding name ="wsHttpBindingCallBack" sendTimeout ="00:00:05"></binding>
- </wsHttpBinding>
- </bindings>
- <behaviors >
- <serviceBehaviors >
- <behavior name="MEX">
- <serviceMetadata />
- </behavior>
- </serviceBehaviors>
- </behaviors>
- </system.serviceModel>
- </configuration>
QQ日志其实真的挺笨的。这和腾迅出的所有产品一样,笨得要死。只是我没有用其他的博客之类的,也犯不着为了一篇文章去申请了。呵呵。其实,细想起来,我们每天离不开的很多东西其实都是粗制品,比如WINDOWS,比如QQ,真的是不用不行,用着着实不爽。呵呵。是不是和我们人生一样,不完美的才是真实的。MSN也好,ICQ也好,其实都比QQ好用得多,但是都死掉了。就拿QQ那个视频来说,真是慢得要死,4M的宽带看高清都不卡,它偏偏要卡,画面只有那么小,真不知腾迅的技术人员是怎么想的。还有那个远程,真是最没用的东西!比起TeamStream差得天上去了。不说了。QQ日志一写多了就犯病。只好把下面的内容再多分几篇了。
6)客户端
配置文件app.config
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
- </startup>
- <system.serviceModel>
- <bindings>
- <netTcpBinding>
- <binding name="NetTcpBinding_IService" closeTimeout="00:01:00"
- openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
- transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
- hostNameComparisonMode="StrongWildcard" listenBacklog="10"
- maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
- maxReceivedMessageSize="65536">
- <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
- maxBytesPerRead="4096" maxNameTableCharCount="16384" />
- <reliableSession ordered="true" inactivityTimeout="00:10:00"
- enabled="false" />
- <security mode="Transport">
- <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
- <message clientCredentialType="Windows" />
- </security>
- </binding>
- </netTcpBinding>
- <wsDualHttpBinding>
- <binding name="wsDualHttpBinding_IService" closeTimeout="00:01:00"
- openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
- transactionFlow="false" hostNameComparisonMode="StrongWildcard"
- maxBufferPoolSize="524288" maxReceivedMessageSize="65536">
- <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
- maxBytesPerRead="4096" maxNameTableCharCount="16384" />
- </binding>
- </wsDualHttpBinding>
- </bindings>
- <client>
- <!--<endpoint address="net.tcp://localhost:8322/Event" binding="netTcpBinding"
- bindingConfiguration="NetTcpBinding_IService" contract="JobServiceClient.IService"
- name="NetTcpBinding_IService">-->
- <endpoint address="http://localhost:8300/Event" binding="wsDualHttpBinding"
- bindingConfiguration="wsDualHttpBinding_IService" contract="JobServiceClient.IService"
- name="wsDualHttpBinding_IService">
- <!--<identity>
- <userPrincipalName value="COMPUTER\Administrator" />
- </identity>-->
- </endpoint>
- </client>
- </system.serviceModel>
- </configuration>
客户端代码(Form) 说明:由于使用了Form作为客户端,就涉及到一个工作线程的问题,因为多线程中使用工作线程是最简单的,也是最便捷的。
- Imports System.Runtime.Serialization
- Imports System.ServiceModel
-
- Public Class Form1
- Implements JobServiceClient.IServiceCallback
-
- Private client As JobServiceClient.ServiceClient
- Private jobList As List(Of JobServiceClient.job) = New List(Of JobServiceClient.job)
-
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
- Dim jobName As String = InputBox("输入新 JOB 名称!")
- If jobName = "" Then
- MessageBox.Show("JOB 名称必须输入!")
- Exit Sub
- End If
-
- Dim newJob As JobServiceClient.job = New JobServiceClient.job()
- newJob.Name = jobName
- newJob.LastRunResult = "Sleeping"
- newJob.LastRunTime = DateTime.Now
- newJob.Status = "Sleeping"
-
- client.AddJob(newJob)
-
- End Sub
-
- Public Sub OnAdd(ByVal newJob As JobServiceClient.job) Implements JobServiceClient.IServiceCallback.OnAdd
- Dim tmpitem As ListViewItem = CreateViewListItem(newJob)
- Me.ListView1.Items.Add(tmpitem)
- End Sub
-
- Public Sub StatusChanged(ByVal job As JobServiceClient.job) Implements JobServiceClient.IServiceCallback.StatusChanged
-
- For Each tmpItem As ListViewItem In Me.ListView1.Items
- If tmpItem.Text = job.Name Then
-
- tmpItem.SubItems(1).Text = job.Status
- tmpItem.SubItems(2).Text = job.LastRunTime.ToString()
- tmpItem.SubItems(3).Text = job.LastRunResult
-
- If job.LastRunResult = "Fail" Then
- tmpItem.ImageIndex = 2
- ElseIf job.Status = "Running" Then
- tmpItem.ImageIndex = 0
- ElseIf job.Status = "Sleeping" Then
- tmpItem.ImageIndex = 1
- Else
- tmpItem.ImageIndex = 1
- End If
- End If
- Next
- End Sub
-
- Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
-
- Try
-
- Dim instanceMe As InstanceContext = New InstanceContext(Me)
- client = New JobServiceClient.ServiceClient(instanceMe)
-
- client.Accept()
-
- LoadJobs()
- Catch ex As Exception
- MessageBox.Show(ex.Message)
- End Try
- End Sub
-
- Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
-
-
- Try
- jobList = client.GetJobs()
- If jobList Is Nothing Then
- Exit Sub
- End If
-
-
- If Me.ListView1.InvokeRequired Then
-
- ListView1.Invoke(New MethodInvoker(AddressOf Me.UpdateViewList))
-
- Else
- Me.UpdateViewList()
- End If
- Catch ex As Exception
- MessageBox.Show(ex.Message)
- End Try
-
-
- End Sub
-
- Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
-
- Me.TextBox1.Text = "获取列表完毕!"
- End Sub
-
- Private Sub LoadJobs()
-
-
- Me.TextBox1.Text = "正在获取JOB列表"
- Me.BackgroundWorker1.RunWorkerAsync()
-
- End Sub
-
- Private Sub UpdateViewList()
-
- Me.ListView1.Items.Clear()
- If jobList.Count < 1 Then
- Me.TextBox1.Text = "JOB列表为空。请先添加JOB。"
- Exit Sub
- End If
- For Each tmpJob As JobServiceClient.job In jobList
- Dim tmpItem As ListViewItem = CreateViewListItem(tmpJob)
- Me.ListView1.Items.Add(tmpItem)
- Next
- End Sub
-
- Private Function CreateViewListItem(ByVal theJob As JobServiceClient.job) As ListViewItem
-
- Dim itemStr() As String = {theJob.Name, theJob.Status, theJob.LastRunTime.ToString(), theJob.LastRunResult}
-
- Dim item As ListViewItem = New ListViewItem(itemStr)
-
- If theJob.LastRunResult = "Fail" Then
- item.ImageIndex = 2
- ElseIf theJob.Status = "Running" Then
- item.ImageIndex = 0
-
-
- Else
- item.ImageIndex = 1
- End If
-
- item.Tag = theJob
-
- Return item
-
- End Function
-
- Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
-
-
-
-
- For Each iIndex As Integer In Me.ListView1.SelectedIndices
- client.DoJob(Me.ListView1.Items(iIndex).Text)
-
- Next
- End Sub
-
- Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
-
- End Sub
-
- Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
-
- End
- End Sub
- End Class
QQ不让传附件,要钱的,马化腾不当官真是可惜。全部代码可到以下地址下载:http://url.cn/GLTdxm
四、总结 要想在服务器端进行事件广播,其实最关键的是,将事件列表保存起来,然后在事件发生时,遍历就好了。然后去通知每一个客户端。在网上的文章 中之所以要用到会话,而且要保持会话状态 就是因只有这样才能在事件异步调用过程中找到自身的客户端回调通道。 而经过验证得之,实际上,只要我们把客户端的回调通道保存在一个共享数组中,这样,我们只要在发生事件时遍历这个数组就可以通知到每个订阅者。所以,我们只需要项目中服务和客户端可以进行回调就可以,这样我们可以使用wsDualHttpBinding进行设计 。而且也可以不用委托或者事件来进行。我们只要把事件状态回调就可以了。而这个回调本身是单向的。也不用异步处理。只要处理好服务器端的并发就可以了。 所以就有了下面的结构:
服务器端进行远程订阅:将订阅的事件和客户端回调通道保存到列表中。 服务器端发生要通知的事件:遍历两个数组进行回调通知。
当然,这个还不很完善,比如,在客户端关闭后,服务器端在回调时会发生异常。如果有大量的客户端关闭或网络异常,会导致服务器端阻滞,当然可以使用多线程 来解决这个问题。
下面是不用事件的服务契约和服务实现(部分代码,完整代码见http://url.cn/GLTdxm,这里的代码就是没有使用委托,也没有使用事件进行的广播。)
(图片丢失)
代码和附件说明:所见的都是最后版本,也就是没有用会话,没有用事件,也没有用委托来实现事件广播的。
注:代码部分因为是360网盘,不知为何已不能使用了。有空传一份到这里。
VB.net Wcf事件广播(订阅、发布)
标签:
原文地址:http://www.cnblogs.com/mqmelon/p/4757507.html