@antoo2013-01-19 18:15:44
User interface
@antoo, 2013-01-19 18:15:44

Another question about background execution of functions?

I am not at all an expert in sharp, moreover, sharp is not my main language (I use it only for programs that strictly require a GUI) and I can’t understand how to do it right after all.
What is required: execution of any actions not in the main thread, i.e. completely eliminate the freezing of the interface.
The program works exclusively with the network, the Internet speeds on the clients are different, many complain.
At the same time, it is necessary to constantly interact with the received data and do it consistently, display changes in the GUI, etc.
I read a lot of Google, everywhere it is recommended to create sheets from callbacks, write huge delegates for all cases, use complex constructions with invokers, and in the current code, which is already not very neat, it is very problematic to redo everything.
Could you share examples of code where some typical synchronous constructs (like getting data, parsing, sending an HTTP request, updating the main window interface, getting again and further parsing) are done in the background, and not just broken into functions? Or at least just explain how to do this with minimal cost and maximum clarity (ie, so that reading the algorithm does not interrupt the sheet of interaction with the main form). Thanks in advance.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Illivion, 2013-01-20

For operations in the background, I advise you to use asynchronous operations. If this is a network, then, for example, BeginSend and BeginWrite. In callbacks, we write the reaction in the GUI. In order for the operation to be performed in the GUI thread, we use the SynchronizationContext. Here is such a simple example:

public partial class SimpleForm : Form
        private readonly SynchronizationContext _context;

        private readonly TcpListener _serverListener;

        private int _connectionsCount;

        public SimpleForm()

            // Зафиксировали GUI-поток
            _context = SynchronizationContext.Current;

            // Включаем ожидание входящих соединений
            _serverListener = new TcpListener(IPAddress.Loopback, 30000);
            _serverListener.BeginAcceptTcpClient(AcceptCallback, null);

        private void AcceptCallback(IAsyncResult ar)
            // Поймали соединение. Завершаем.
            var client = _serverListener.EndAcceptTcpClient(ar);

            // Сообщаем о новом подключении.

        private void AddConnection()
            // Увеличиваем счетчик подключений
            Interlocked.Add(ref _connectionsCount, 1);

            // Сообщаем лейблу на форме новое значение. Используем GUI-поток, ибо в Callback'е находимся в чужом потоке из пула.

            _context.Post(state => { lbConnCount.Text = _connectionsCount.ToString(); }, null);

Dmitry Guketlev, 2013-01-20

In C# 5.0 and .NET 4.0, the wonderful async\await appeared, completely removing the callback sheets. Read about them.

codecity, 2013-01-19

Or at least just explain how to do it with minimal cost and maximum clarity.

Probably the question is similar to "what type to use in C++ for strings". In this regard, C # has grown so much, so many options are more beautiful than each other - that it is difficult to give unambiguous advice.
The simplest, of course, is the new async + await construct. But in C#4, you need to install AsyncCTP.

brainx64, 2013-02-23

In the days of .NET 2.0, I used System.ComponentModel.BackgroundWorker for background tasks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question