AutoResetEvent如何在列表视图中写入

本文关键字:视图 列表 AutoResetEvent | 更新日期: 2023-09-27 18:22:14

如何在名为"LivStapaEventi"的listview上编写我会实时将事件写入事件日志窗口,我应该使用代理,如果是,你能告诉我如何使用吗?感谢大家

  Private Shared signal As AutoResetEvent
Private Sub Form1_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
    scelta = ""
    Me.Thread = New Thread(New ThreadStart(AddressOf Me.Threaddammiora)) 'creo il thread
    Me.Thread.Start() 'lancio il thread
    width_rem = LivStampaEventi.Width
    Height_rem = LivStampaEventi.Height
    Dim remoteEventLogs() As EventLog
    Dim log As EventLog
    For Each log In remoteEventLogs
        cmb_tutti_i_log.Items.Add(log.Log)
    Next log
    signal = New AutoResetEvent(False)
    Dim myNewLog As New EventLog("PMIS_A2A", System.Environment.MachineName)
    AddHandler myNewLog.EntryWritten, AddressOf Me.MyOnEntryWritten
    myNewLog.EnableRaisingEvents = True
    myNewLog.WriteEntry("PMIS_A2A", EventLogEntryType.Information)
    signal.WaitOne()
End Sub

Public Sub MyOnEntryWritten(ByVal [source] As Object, ByVal e As EntryWrittenEventArgs)
    Console.WriteLine("In event handler")
    signal.Set()
    Dim list As New List(Of String)
    list.Clear()
    list.Add(e.Entry.EventID.ToString())
    list.Add(e.Entry.Message.ToString())
    list.Add(e.Entry.EntryType.ToString())
    list.Add(e.Entry.TimeWritten.ToString())
    list.Add(e.Entry.TimeGenerated.ToString())
    list.Add(e.Entry.Index.ToString())
    LivStampaEventi.Items.Add(New ListViewItem(list.ToArray))
    If (e.Entry.EntryType.ToString = "Warning") Then
        LivStampaEventi.Items(LivStampaEventi.Items.Count - 1).BackColor = Color.Yellow
    Else
        If (e.Entry.EntryType.ToString = "Error") Then
            LivStampaEventi.Items(LivStampaEventi.Items.Count - 1).BackColor = Color.Red
        Else
            LivStampaEventi.Items(LivStampaEventi.Items.Count - 1).BackColor = Color.Green
        End If
    End If
End Sub ' MyOnEntryWritten

AutoResetEvent如何在列表视图中写入

您似乎正试图从非UI线程设置list属性,这会导致出现异常。您引用的MSDN链接提供了一个解决方案:在MyOnEntryWritten中,测试InvokeRequired

If list.InvokeRequired then // true if not in the UI thread
    list.Invoke(...) // use a delegate for MyOnEntryWritten 
Else
    // the actual code
End If

要为Invoke创建参数,请检查链接