开发者

Using stream.beginwrite to achieve fire-and-forget REST call?

开发者 https://www.devze.com 2023-03-23 13:22 出处:网络
I am attempting to call a RESTful service but I do not really want to even wait for the response (200/404/500).

I am attempting to call a RESTful service but I do not really want to even wait for the response (200/404/500).

I know this may sound trivia开发者_开发问答l but, I have a unique scenario that, for some reason requires this. I have made my request like so:

        using (Stream stream = webRequest.GetRequestStream())
        {
            stream.BeginWrite(postData, 0, postData.Length, null, null);
        }

This appears to work but just feels wrong. Is this frowned-upon behavior? If so, what would be a preferred method?

Thanks in advance


See MSDN:

EndWrite must be called once for every call to BeginWrite. You can do this either by using the same code that called BeginWrite or in a callback passed to BeginWrite.

So by itself, no - this could cause a leak. Also, though, if you start an async write, and dispose the stream immediately, the write is almost certainly to a closed/disposed stream (it is exceptionally unlikely that the second thread has even got involved at that point, let alone completed the write). Perhaps start a Task or ThreadPool item that does a regular Write?

ThreadPool.QueueUserWorkItem(delegate {
    using (Stream stream = webRequest.GetRequestStream()) {
        stream.Write(postData, 0, postData.Length);
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消