Invoking Delegate in a Console Application

情到浓时终转凉″ 提交于 2019-12-11 07:04:27

问题


I need to migrate a WinForm Application to a Console Application.

In the WinForm Application, I have something like:

this.Invoke(new LogResponseCallback(this.LogResponse), new object[] { allAlarmsJson });


   private delegate void LogResponseCallback(string text);
    private void LogResponse(string response)
    {
        this._richTextResponse.Text = response + "\r\n";
    }

Seems like Main Thread has been called after the processing of a certain operation.

My concern is how can the same Asynchronous delegate call can be achieved in the Console application.

Any help would be highly appreciated.

Thanks in advance


回答1:


Here is a question I asked about how Invoke does what it does,

Curious about the implementation of Control.Invoke()




回答2:


Normally in Windows Forms you'd use Control.Invoke to get back to the UI thread from a background thread, as you can't access UI controls within a non-UI thread.

The same restriction doesn't apply in a console application - you may still need to be careful to avoid threading issues, but they're unlikely to be the same issues. If all you're doing is logging to the console (e.g. with Console.WriteLine) you should be fine to just do the logging in the background thread.




回答3:


First of all you are not using any asynchonous delegate in your code here, the this.Invoke is synchronous call.
Second if you are running Console application you don't have to marshal the call back to the main thread, You only should do so when you are executing code that relying on thread, such as winforms, wpf UI thread and some COM components, you only have to marshal call in these situations because these components are relying on the thread that created them



来源:https://stackoverflow.com/questions/7011886/invoking-delegate-in-a-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!