0

I am trying to upload a file through stream to azure file share. This is my function :

public static async Task UploadFile(string shareName, Stream content, string fileName, string dirName)
        {
            var shareClient = Common.CreateSMBClientFromConnectionString(shareName);
            ShareDirectoryClient directory = shareClient.GetDirectoryClient(dirName);
            ShareFileClient file = directory.GetFileClient(fileName);
            await file.CreateAsync(content.Length);
            await file.UploadAsync(content);
        }

I calling this function by the following command:

SMBHelper.UploadFile("filesharetester", rps, "hereischecking.txt", "checking/lp").GetAwaiter();

The program shows no error but while debugging the program I see that the pointer get lost whenever statement containing await arrives. Like in this case program automatically stopped working when statement await file.CreateAsync(content.Length); arrives.

Zer0
  • 7,191
  • 1
  • 20
  • 34
Psychonaut007
  • 167
  • 3
  • 13
  • 1
    have you got an `await` on the function call itself? – JamesS Apr 29 '22 at 11:17
  • I have added many nuget packages. It is possible that it is getting conflicted with another ```await``` keyword? – Psychonaut007 Apr 29 '22 at 11:18
  • @JamesS No I am using getAwaiter() whenever i am calling asynchronous function – Psychonaut007 Apr 29 '22 at 11:19
  • why not `await SMBHelper.UploadFile(...)`. I see GetAwaiter(), are you awaiting on that? I do not see you storing a return value so my guess is no. That's your problem. Calling GetAwaiter() by itself is basically a no-op if you aren't using the return value. – Zer0 Apr 29 '22 at 11:21
  • I am just curious to know why it is not working with GetAwaiter(). Like I know getAwaiter() makes function caller method work synchronous and will let let function execution get completed, then what's the issue? – Psychonaut007 Apr 29 '22 at 11:23
  • No, [it does not](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.getawaiter?view=net-6.0) as I already mentinoed. Note the return value you aren't using. And the name speaks or itself. If you get an awaiter, you need to await on it. – Zer0 Apr 29 '22 at 11:25
  • You should call `RunSynchronously`. – shingo Apr 29 '22 at 12:39

1 Answers1

0

The most likely explanation is that file.CreateAsync fails. That will cause the returned task to also fail. But since you do not check the result of the returned task, you will never know about the failure. This can be fixed by awaiting the task and using try/catch to handle any errors:

try{
    await SMBHelper.UploadFile(...)
}
catch(Exception e){
    // Handle error
}

Another possibility might be that the file.CreateAsync just never completes, you should be able to use the Task-view in visual studio to check for this.

JonasH
  • 28,608
  • 2
  • 10
  • 23