如何为后台工作人员传递功能?

时间:2018-11-07 18:33:46

标签: c# backgroundworker

我想创建一个函数,以便每次需要在backgroundWorker中运行该函数时都可以将该函数传递给调用。像这样。

void RunInBackgroundWorker(Func<object, DoWorkEventArgs, bool> do_work)
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += do_work;
    worker.ProgressChanged += Worker_ProgressChanged;
    worker.WorkerReportsProgress = true;
    worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
    worker.RunWorkerAsync();
}

但是Visual Studio抱怨说它不能将类型'System.Func'隐式转换为'System.ComponentModel.DoWorkEventHandler'

可以通过这种方式做到吗?如何正确传递函数?

2 个答案:

答案 0 :(得分:2)

Imports System.Data.SqlClient
Public Class Form1
    Dim sCommand As SqlCommand
    Dim sAdapter As SqlDataAdapter
    Dim sBuilder As SqlCommandBuilder
    Dim sDs As DataSet
    Dim sTable As DataTable

    Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
        Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
        Dim sql As String = "SELECT * FROM Stores"
        Dim connection As New SqlConnection(connectionString)
        connection.Open()
        sCommand = New SqlCommand(sql, connection)
        sAdapter = New SqlDataAdapter(sCommand)
        sBuilder = New SqlCommandBuilder(sAdapter)
        sDs = New DataSet()
        sAdapter.Fill(sDs, "Stores")
        sTable = sDs.Tables("Stores")
        connection.Close()
        DataGridView1.DataSource = sDs.Tables("Stores")
        DataGridView1.ReadOnly = True
        save_btn.Enabled = False
        DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect

    End Sub

    Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
        DataGridView1.[ReadOnly] = False
        save_btn.Enabled = True
        new_btn.Enabled = False
        delete_btn.Enabled = False
    End Sub

    Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
        If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
            DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
            sAdapter.Update(sTable)
        End If
    End Sub

    Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
        sAdapter.Update(sTable)
        DataGridView1.[ReadOnly] = True
        save_btn.Enabled = False
        new_btn.Enabled = True
        delete_btn.Enabled = True
    End Sub
End Class

这也与WPF无关。

答案 1 :(得分:0)

我实际上解决了它。我没有传递功能(Func do_work),而是传递了(DoWorkEventHandler do_work),它起作用了!