Skip to main content
 首页 » 编程设计

c#之将 MSDN 示例从 C# 转换为 C++/CLI

2024年02月23日10lori

这是来自 Microsoft(MSDN) 的代码示例 (build sql dependency application) , 你能帮我把这段代码从 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; 
 
} 

请您参考如下方法:

这是我的快速尝试:

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