我正在使用 HttpSelfHostServer 来托管我的 WebApi。我像这样返回 PushStreamContent
public HttpResponseMessage Get(HttpRequestMessage request)
{
var response = request.CreateResponse();
response.Content = new PushStreamContent(OnStreamAvailable, "text/eventstream");
return response;
}
在我向我的 api 发出第二个请求之前,一切都按预期工作。第一个请求被阻塞,第二个请求在我关闭第一个请求之前不会到达 Get-function。
我已经像这样设置了我的配置
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
config.TransferMode = System.ServiceModel.TransferMode.Streamed;
config.MaxConcurrentRequests = 10;
为什么第一个电话会阻塞第二个电话?
编辑:这是我的完整控制器:
public class PushController : ApiController
{
private static readonly ConcurrentBag<StreamWriter> _Writers = new ConcurrentBag<StreamWriter>();
public HttpResponseMessage Get(HttpRequestMessage request)
{
var response = request.CreateResponse();
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Cache-Control", "no-cache, must-revalidate");
response.Content = new PushStreamContent(OnStreamAvailable, "text/event-stream");
return response;
}
private void OnStreamAvailable(Stream stream, HttpContent content, TransportContext context)
{
_Writers.Add(new StreamWriter(stream) { AutoFlush = true });
}
public static void Say(string text)
{
try
{
foreach (var w in _Writers)
{
w.Write("data:{ text : \"" + text + "\" }\n\n");
}
}
catch { }
}
}