开发者

Translate MSDN example from C# to C++/CLI

this is a code sample from Microsoft(MSDN) (build sql dependency application) , could you please help me translate this code from c# into C++/CLI, I've been trying I, but I'm not really good in c++.

private void dependency_OnC开发者_运维百科hange(
   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;

}


Here's my quick attempt:

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();

}


Compile the C# sample source code, then use Reflector to decompile the assembly to MC++ (managed C++).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜