简体   繁体   中英

Calling an Async method in a C# library from a VB main method

My application is written in VB.net and for reasons beyond my control, I cannot change the technology. I am trying to use AWS S3 buckets to store files. My application in VB will need to show a window which lists files in a bucket and enable the users to download them.

The listing of files in S3 is done using an Async Task using C#

 public async Task<List<string>> listAllContentsAsync()
        {
            List<string> contents = new List<string>();
            client = new AmazonS3Client(bucketRegion);
            ListObjectsV2Request request = new ListObjectsV2Request
            {
                BucketName = bucketName,
                MaxKeys = 20
            };

            ListObjectsV2Response response;
            do
            {
                response = await client.ListObjectsV2Async(request);

                foreach (S3Object entry in response.S3Objects)
                {
                    String contentName = entry.Key.Split('.')[0];
                    contents.Add(contentName);
                }

                request.ContinuationToken = response.NextContinuationToken;
            } while (response.IsTruncated);

            return contents;
        }

I then create a dll for the project in C# and reference it in the VB project. Just for a POC I created a sample VB project which would instantiate an object and call the listAllContentsAsync method to list contents.

I had to change the signature of the Main method because the function I am calling is Async . Here is the updated Main method in VB:

Async Function Main() As Task(Of Task)
    Dim objcsClass = New CallMeFromVB.ClassInCSharpProject()
    Dim inputChar As ConsoleKeyInfo = Console.ReadKey()
    Dim contents As New List(Of String)

    contents = Await objcsClass.listAllContentsAsync()
    For Each content As String In contents
        Console.Write(content & " ")
    Next

End Function

Now, when I try to run my VB project, I get an error saying that there is no Main method in the project. Is there a way I can call an Async method ( listAllContentsAsync ) from the VB Main method?

Just turn it syncronous:

Sub Main() 
    Dim objcsClass = New CallMeFromVB.ClassInCSharpProject()
    Dim inputChar As ConsoleKeyInfo = Console.ReadKey()
    Dim contents As New List(Of String)
    contents = objcsClass.listAllContentsAsync().GetAwaiter().GetResult()
    For Each content As String In contents
        Console.Write(content & " ")
    Next

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM