C# - Can you run a task and return to the main thread later?

Asked

Viewed 259 times

0

in the case the whole program is written without task and only one excerpt is with task, I wanted after that piece it returned to the "main thread". The code below is inside a for, and serves to open a save window, the task specifically operates this window, it starts even before the window is opened because when it opens the program "stops reading the code". Remember that the save window is not a savefileDialog, it is opened using the webbrowser tool of c# calling a click on a download button.

Clipboard.SetText(@"C:\ARQUIVOS\");

            Task t = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                SendKeys.SendWait("{HOME}");
                SendKeys.SendWait("^{V}");
                Thread.Sleep(1000);
                SendKeys.SendWait("{ENTER}"); //esse enter salva o arquivo, depois disso o programa fica em "standby" pois acaba a thread e nao volta para o codigo principal 
                Task.Delay(3000);

            });

            await Task.Delay(3000);

            SendKeys.SendWait("{TAB}");
            SendKeys.SendWait("{TAB}");
            SendKeys.SendWait("{TAB}");
            SendKeys.SendWait("{ENTER}");  //abre janela de salvar
            FileIOPermission.RevertAll();  //permissões para a janela
            Task.Delay(3000);

EDIT: I got it with the following code:

    private async Task OperaJanelaSaveAs()
    {
        Clipboard.SetText(@"C:\ARQUIVOS\");

        SendKeys.SendWait("{TAB}");
        SendKeys.SendWait("{TAB}");
        SendKeys.SendWait("{TAB}");
        SendKeys.SendWait("{ENTER}");  //abre janela de salvar
        await Task.Delay(4000);
        SendKeys.SendWait("{HOME}");
        SendKeys.SendWait("^{V}");    //cola o caminho do arquivo (clipboard) 
        await Task.Delay(3000);
        SendKeys.SendWait("{ENTER}"); //salva o arquivo
        await Task.Delay(4000);
    }

and calling the delay function to wait for the click on the download button and await

await Task.Delay(6000);
await OperaJanelaSaveAs();
  • This is very confusing, put your code to understand better

  • And that’s not exactly why you use a Task?

  • @Maniero yes but the code is terminated after the task

  • @Ricardopunctual I put

  • I saw no sense in using this task with your need.

  • 1

    That pile of Thread.Sleep() already shows that this code makes no sense and is doing wrong things. We do not know exactly what you want to do, but it seems wrong choice

  • @Victorlaio as I said when I open the save window the program understands that there is no more code to read so the task is already running and operates the window

  • I suggest not to put sensitive data in the examples. For example IP!

  • @phduarte Dude, it’s a local IP, there’s nothing sensitive about it.

  • @Miltonmachadopereira Try [Dit] your question and be clearer. Explain what you intend to do.

  • @LINQ sees if it gets better

  • @LINQ If I worked at the same company now I would know where the Billing files are saved!

  • @Miltonmachadopereira this window that opens to save. It is a web page or a Windows window?

  • @phduarte windows window opened from a boot of an open site in the webbrowser tool of c#

  • @Miltonmachadopereira you are probably using this Task because you don’t know exactly how long it will take for the Save window to appear, and you don’t want the system to be in a "Not responding" state or anything. Correct?

  • @phduarte to expect sleeps and delays. The problem in question is that after you save the file nothing else happens, and as I said the code in question is along with more code everything inside a for and is not going to the next repeat.

  • @Miltonmachadopereira as he is having no problem with the status Not responding and is using Sleeps in several snippets, I can’t see the benefit of using the multithreads. It seems to be getting in your way more than helping. I usually do things similar to saving files using thread, but I don’t use Sleep or Sendkeys, I do it using Windows' own api, I also use a Boolean variable to control the completion before I proceed to code execution.

Show 12 more comments

2 answers

1


Look... is very confused your question but the information I was able to extract follows: This if you have available . NET Framework 4.0+

public async Task DoWork()
{
    Clipboard.SetText(@"\\192.168.30.158\ARQUIVOS\");

    await Task.Run(async () =>
    {
        await Task.Delay(5000);
        SendKeys.SendWait("{HOME}");
        SendKeys.SendWait("^{V}");
        await Task.Delay(1000);
        SendKeys.SendWait("{ENTER}"); //esse enter salva o arquivo, depois disso o programa fica em "standby" pois acaba a thread e nao volta para o codigo principal 
        await Task.Delay(3000);
    });

    await Task.Delay(3000);

    SendKeys.SendWait("{TAB}");
    SendKeys.SendWait("{TAB}");
    SendKeys.SendWait("{TAB}");
    SendKeys.SendWait("{ENTER}");  //abre janela de salvar

    FileIOPermission.RevertAll();  //permissões para a janela

    await Task.Delay(3000);
}
  • Dude, asynchronously (with your code) I can keep the code running after you run the task, but it doesn’t download the file. and synchronously I can download the file but I can’t get back to the code after the task round. I think you’re waiting at the wrong time using the code pad you sent.

  • Much simpler to perform functions than tasks, mainly by calling the function again

  • @riki481 as I mentioned, is very confusing the question. The most I could get with the information I had and understood, was the code above. You probably have better ways of doing it but not with the information I received from the question.

0

See an example to save file back to the main system stream after thread execution.

With some modifications you can adapt to your scenario.

public void SalvarArquivo()
{
    //faz as ações antes de salvar o arquivo
    Console.WriteLine("Preparando arquivo para salvar");

    var task = Task.Factory.StartNew(() =>
    {
        for (var i = 10; i >= 0; i--)
        {
            Console.Write("\rSalvando arquivo. Aguarde {0} segundos", i);
            Thread.Sleep(1000);
        }
        Console.WriteLine();
    });

    task.Wait();

    //faz as ações após conclusão
    Console.WriteLine("Arquivo salvo com sucesso.\nPressione Enter para sair.");
    Console.ReadLine();
}

or

async void Do()
{
    await SalvarArquivoAsync();
}

public async Task SalvarArquivoAsync()
{
    //faz as ações antes de salvar o arquivo
    Console.WriteLine("Preparando arquivo para salvar");

    await Task.Factory.StartNew(() =>
    {
        for (var i = 10; i >= 0; i--)
        {
            Console.Write("\rSalvando arquivo. Aguarde {0} segundos", i);
            Thread.Sleep(1000);
        }
        Console.WriteLine();
    });

    //faz as ações após conclusão
    Console.WriteLine("Arquivo salvo com sucesso.\nPressione Enter para sair.");
    Console.ReadLine();
}
  • I need the thread to start asynchronously and finish synchronously

Browser other questions tagged

You are not signed in. Login or sign up in order to post.