-1

ina c# project i have a static async task written to send emails via tmpt-relay. the main function is calling this task. This is working fine. My Problem is i'm calling this function from a vb.net project, this is also working, email was send but vb.net is hanging in the c#-call

My Code in c#

public class SmoffMail
    {
        public static string sRet;

        public string sendMail(string mailto)
        {
            RunAsync(mailto).Wait();
            return sRet;
        }

       static async Task RunAsync(string mailto){

            MailjetClient client = new MailjetClient("419cce0b9807d1016642156966fc4ec1", 
            ....    
        
            sRet = "ok.....";
        }
    }

From the vb.net i call it like this:

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim smail As New smoff.Mailjet.SmoffMail
        Dim i As Integer = 0
        Dim sRet As String = ""

        sRet = smail.sendMail("xxxxxxxh@bluewin.ch")

        MsgBox(sRet)

    End Sub
End Class

So the function smail.sendMail() was called but is hanging, the next line in code ( msgbox ) is nerver attempt.

Thanks for your help

Mary
  • 14,926
  • 3
  • 18
  • 27
  • 2
    RunAsync().Wait() is something you have to do in a console mode app. In a winforms app it [will deadlock](https://stackoverflow.com/questions/13140523/await-vs-task-wait-deadlock). – Hans Passant Oct 04 '20 at 10:04
  • Re Hans's comment, also see Stephen Cleary's blog post: https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html – Craig Oct 05 '20 at 14:04
  • All the benefits of async.. thrown away – Caius Jard Oct 07 '20 at 08:14

2 Answers2

0

Your C# should look like this:

public class SmoffMail
{

   static async Task<string> SendMailAsync(string mailto){

        MailjetClient client = new MailjetClient("419cce0b9807d1016642156966fc4ec1", 
        ....    
    
        return "ok.....";
    }
}

And your VB should look like this:

Public Class Form1
    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim sRet As String = ""

        sRet = Await smoff.Mailjet.SmoffMail.SendMailAsync("xxxxxxxh@bluewin.ch")

        MsgBox(sRet)

    End Sub
End Class

Let your VB go back to drawing the UI while it waits for your 2 gigabyte attachment to upload, otherwise there's no point in having any of this be async

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
-1

i found the solution, the problem was not my code, it was the API Mailjet.client. after changing the call to this API it works fine

  • 3
    Changing how? It would be a lot more useful to future readers if you actually show specifically what the changed code is – ADyson Oct 04 '20 at 12:19