2

我有一个带有一些条目的 C# ListView、一个删除第一个条目的 Methode 和一个调用此方法的 Timer。我的问题是,计时器运行良好(我通过调用 MessageBox 进行了检查)并且 remove 方法也运行良好(我通过使用 Button 而不是计时器调用此方法来检查)。但是计时器仍然不能从我的 ListView 中删除项目。

我的代码:

    void Button1Click(object sender, EventArgs e)
    {
        removeItems();
    }

    private void timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
    {
        removeItems();      
    }

    void removeItems()
    {
        MessageBox.Show("Hello from the removeMethod");
        listViewTeam.Items.RemoveAt(0);
    }

removeItems() 的两个调用;让messageBox出现,但只有Button让我们也删除listView的第一个项目。

有人可以帮助我如何通过计时器删除第一个项目吗?

4

7 回答 7

2

您使用的计时器不是线程安全的。System.Timer您应该使用而不是使用,System.Windows.Forms.Timer因为它会自动在 UI 线程上运行。然后您的代码将完美运行。

于 2013-06-13T11:01:49.017 回答
1

您似乎正在使用System.Timer这意味着您的Elapsed回调不一定会在 UI 线程上调用。Invoke您可以通过使用ie来确保它确实如此

if (listViewTeam.InvokeRequired)
{
    listViewTeam.Invoke((MethodDelegate)delegate { listViewTeam.Items.RemoveAt(0); });
}

或者更容易将计时器的SynchronizingObject属性设置为包含您的表单,ListView并且您的代码将正常工作。

于 2013-06-13T11:02:58.707 回答
0

您需要使用 adelegate从后台线程安全地与 UI 控件交互(这是您在实现 a 时真正Timer在做的事情):

void Button1Click(object sender, EventArgs e)
{
    removeItems();
}

private void timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
    removeItems();      
}

void removeItems()
{
    MessageBox.Show("Hello from the removeMethod");
    RemoveListViewItem(0);
}

public delegate void InvokeRemoveListViewItem(Int32 ItemIndex);
public void RemoveListViewItem(Int32 ItemIndex)
{
    if (InvokeRequired)
    {
        try { Invoke(new InvokeRemoveListViewItem(RemoveListViewItem), new Object[] { ItemIndex }); }
        catch (Exception)
        {
            //react to the exception you've caught
        }
    }

    listView.RemoveAt(ItemIndex);
}
于 2013-06-13T11:04:05.430 回答
0

就像 SLC 说你需要使用 BeginInvoke。我个人已经这样解决了

  public AddListItem myDelegate;
于 2013-06-13T11:08:07.647 回答
0
                               Windows.Forms       System.Timers         System.Threading 
Timer event runs on what thread?    UI thread      UI or worker thread   Worker thread 
Instances are thread safe?          No             Yes                   No 
Familiar/intuitive object model?    Yes            Yes                   No 
Requires Windows Forms?             Yes            No                    No 
Metronome-quality beat?             No             Yes*                  Yes* 
Timer event supports state object?  No             No                    Yes 
Initial timer event schedulable?    No             No                    Yes 
Class supports inheritance?         Yes            Yes                   No

* Depending on the availability of system resources (for example, worker threads) 
于 2015-09-11T12:57:58.940 回答
-1

首先启动计时器。但是使用Windows 窗体计时器。

您的设计师课程:

partial class Form1
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.listBox1 = new System.Windows.Forms.ListBox();
        this.timer1 = new System.Windows.Forms.Timer(this.components);
        this.SuspendLayout();
        // 
        // listBox1
        // 
        this.listBox1.FormattingEnabled = true;
        this.listBox1.Items.AddRange(new object[] {
        "q",
        "w",
        "e",
        "r",
        "t",
        "y",
        "u",
        "sfdgsdf",
        "gf",
        "gsd",
        "fgs",
        "dfg"});
        this.listBox1.Location = new System.Drawing.Point(170, 200);
        this.listBox1.Name = "listBox1";
        this.listBox1.Size = new System.Drawing.Size(120, 95);
        this.listBox1.TabIndex = 0;
        // 
        // timer1
        // 
        this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(570, 502);
        this.Controls.Add(this.listBox1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.Timer timer1;
}

你的表单类:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        removeItems();
        if (listBox1.Items.Count == 0)
        {
            timer1.Stop();
        }
    }

    void removeItems()
    {
        MessageBox.Show("Hello from the removeMethod");
        listBox1.Items.RemoveAt(0);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1.Start();
    }
}
于 2013-06-13T11:03:06.303 回答