1

这是来自 Microsoft(MSDN) 的代码示例(构建 sql 依赖应用程序),你能帮我把这段代码从 c# 翻译成 C++/CLI,我一直在尝试,但我不太擅长 c++。

private void dependency_OnChange(
   object sender, SqlNotificationEventArgs e)
{
    // This event will occur on a thread pool thread.
    // Updating the UI from a worker thread is not permitted.
    // The following code checks to see if it is safe to
    // update the UI.
    ISynchronizeInvoke i = (ISynchronizeInvoke)this;

    // If InvokeRequired returns True, the code
    // is executing on a worker thread.
    if (i.InvokeRequired)
    {
        // Create a delegate to perform the thread switch.
        OnChangeEventHandler tempDelegate =
            new OnChangeEventHandler(dependency_OnChange);

        object[] args = { sender, e };

        // Marshal the data from the worker thread
        // to the UI thread.
        i.BeginInvoke(tempDelegate, args);

        return;
    }

    // Remove the handler, since it is only good
    // for a single notification.
    SqlDependency dependency =
        (SqlDependency)sender;

    dependency.OnChange -= dependency_OnChange;

    // At this point, the code is executing on the
    // UI thread, so it is safe to update the UI.
    ++changeCount;
    label1.Text = changeCount;

}
4

2 回答 2

3

这是我的快速尝试:

private void dependency_OnChange(
   System::Object^ sender, SqlNotificationEventArgs^ e)
{
    // This event will occur on a thread pool thread.
    // Updating the UI from a worker thread is not permitted.
    // The following code checks to see if it is safe to
    // update the UI.
    ISynchronizeInvoke^ i = this;

    // If InvokeRequired returns True, the code
    // is executing on a worker thread.
    if (i->InvokeRequired)
    {
        // Create a delegate to perform the thread switch.
        OnChangeEventHandler^ tempDelegate =
            gcnew OnChangeEventHandler(this, &Form1::dependency_OnChange);

        cli::array<System::Object^>^ args = gcnew cli::array<System::Object^>(2);
        args[0] = sender;
        args[1] = e;

        // Marshal the data from the worker thread
        // to the UI thread.
        i->BeginInvoke(tempDelegate, args);

        return;
    }

    // Remove the handler, since it is only good
    // for a single notification.
    SqlDependency^ dependency = safe_cast<SqlDependency^>(sender);

    dependency->OnChange -= gcnew OnChangeEventHandler(this, &Form1::dependency_OnChange);

    // At this point, the code is executing on the
    // UI thread, so it is safe to update the UI.
    ++changeCount;
    label1->Text = changeCount.ToString();

}
于 2011-04-07T22:39:09.730 回答
1

编译 C# 示例源代码,然后使用Reflector将程序集反编译为 MC++(托管 C++)。

于 2011-04-07T21:12:37.073 回答