无法读取响应AsStream,因为我在.NET MAUI BLAZOR中获得NetworkOnMainThreadException

e7arh2l6  于 2023-05-19  发布在  .NET
关注(0)|答案(1)|浏览(142)

我无法读取为流,因为我收到NetworkOnMainThreadException错误。
这是我的代码:

string requestRoot = JsonConvert.SerializeObject(requestToSerialize);
        var content = new StringContent(requestRoot, Encoding.UTF8, "application/json");
        var request = new HttpRequestMessage(HttpMethod.Post, _httpClient.BaseAddress)
        {
            Content = content
        };
        var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
        var streamReader = new StreamReader(await response.Content.ReadAsStreamAsync());
        var sb = new StringBuilder();
        try
        {
            while (!streamReader.EndOfStream)
            {
                var line = await streamReader.ReadLineAsync();

                if (line!.StartsWith("data:"))
                {
                    if (!line.Contains("[DONE]"))
                    {
                        var data = line.Substring(5).Trim();
                        WEBAPP.Entities.Root root = JsonConvert.DeserializeObject<WEBAPP.Entities.Root>(data);

                        if (root.choices[0].delta.content != null)
                        {
                            RequestLog.content = root.choices[0].delta.content;
                        }
                        if (root.choices[0].delta.role != null)
                        {
                            RequestLog.role = root.choices[0].delta.role;
                        }
                        RequestLog.index = root.choices[0].index;

                        if (data == "[DONE]")
                        {
                            break;
                        }

                        JObject dataObj = JObject.Parse(data);
                        string contentValue = (string)dataObj["choices"][0]["delta"]["content"];
                        Response += contentValue;
                        StateHasChanged();
                        Thread.Sleep(170);

                        Console.WriteLine(line);

                        sb.Append(contentValue);
                    }
                }
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

我得到了这个错误:

{Android.OS.NetworkOnMainThreadException: Exception of type 'Android.OS.NetworkOnMainThreadException' was thrown.
   at Java.Interop.JniEnvironment.InstanceMethods.CallIntMethod(JniObjectReference instance, JniMethodInfo method, JniArgumentValue* args) in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/obj/Release/net7.0/JniEnvironment.g.cs:line 11725
   at Java.Interop.JniPeerMembers.JniInstanceMethods.InvokeVirtualInt32Method(String encodedMember, IJavaPeerable self, JniArgumentValue* parameters) in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods_Invoke.cs:line 511
   at Java.IO.InputStream.Read(Byte[] b, Int32 off, Int32 len) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/net7.0/android-33/mcw/Java.IO.InputStream.cs:line 282
   at Android.Runtime.InputStreamInvoker.Read(Byte[] buffer, Int32 offset, Int32 count) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/InputStreamInvoker.cs:line 89
   at System.IO.BufferedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.DelegatingStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.StreamReader.ReadBuffer()
   at System.IO.StreamReader.get_EndOfStream()
   at CHAT.Pages.Index.SendRequest() in C:\Users\Mr.Sepi0l\Desktop\MAUI\CHAT\CHAT\Pages\Index.razor.cs:line 85
  --- End of managed Android.OS.NetworkOnMainThreadException stack trace ---
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1667)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:431)
    at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.processDataFromSocket(ConscryptEngineSocket.java:836)
    at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.readUntilDataAvailable(ConscryptEngineSocket.java:824)
    at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.read(ConscryptEngineSocket.java:797)
    at com.android.okhttp.okio.Okio$2.read(Okio.java:138)
    at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:213)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:307)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:301)
    at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:197)
    at com.android.okhttp.internal.http.Http1xStream$ChunkedSource.readChunkSize(Http1xStream.java:453)
    at com.android.okhttp.internal.http.Http1xStream$ChunkedSource.read(Http1xStream.java:437)
    at com.android.okhttp.okio.RealBufferedSource$1.read(RealBufferedSource.java:372)
    at mono.java.lang.RunnableImplementor.n_run(Native Method)
    at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:31)
    at android.os.Handler.handleCallback(Handler.java:942)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:201)
    at android.os.Looper.loop(Looper.java:288)
    at android.app.ActivityThread.main(ActivityThread.java:7872)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

  --- End of managed Android.OS.NetworkOnMainThreadException stack trace ---
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1667)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:431)
    at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.processDataFromSocket(ConscryptEngineSocket.java:836)
    at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.readUntilDataAvailable(ConscryptEngineSocket.java:824)
    at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.read(ConscryptEngineSocket.java:797)
    at com.android.okhttp.okio.Okio$2.read(Okio.java:138)
    at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:213)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:307)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:301)
    at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:197)
    at com.android.okhttp.internal.http.Http1xStream$ChunkedSource.readChunkSize(Http1xStream.java:453)
    at com.android.okhttp.internal.http.Http1xStream$ChunkedSource.read(Http1xStream.java:437)
    at com.android.okhttp.okio.RealBufferedSource$1.read(RealBufferedSource.java:372)
    at mono.java.lang.RunnableImplementor.n_run(Native Method)
    at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:31)
    at android.os.Handler.handleCallback(Handler.java:942)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:201)
    at android.os.Looper.loop(Looper.java:288)
    at android.app.ActivityThread.main(ActivityThread.java:7872)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
}

我在.NET 7中使用.NET MAUI BLAZOR。有人解决这个问题吗?
我正在尝试一些与任务。运行,但我仍然只得到第一个字符从响应,没有更多。也许你们中的某个人能渡过难关并提供帮助?:—)

编辑

这是前端:

@page "/"

<div class="container">
    <div class="response-container" style="padding:10px;">
        @if(Question != "")
        {
            <div class="card" style="background-color:#343541;">
                <h6 class="card-header" style="background-color:#59595c;color:white; text-align:center;">@Question</h6>
                <div class="card-body">
                    <p class="card-text">
                        @if (!string.IsNullOrEmpty(Response))
                        {
                            <pre>
                                 <code>
                                   @((MarkupString)RenderMarkdown(Response))
                                 </code>
                            </pre>
                        }
                    </p>
                </div>
            </div>
        }
    </div>
</div>
<div class="container-fluid">
    <div class="edit-form">
        <EditForm id="editForm" Model="@Message" OnValidSubmit="SendRequest" OnInvalidSubmit="Invalid" class="edit-form">
            <DataAnnotationsValidator />
            <p>
                <InputTextArea 
                    @onkeyup="Enter"
                    @oninput="Input"
                               @bind-Value="message"
                    style="background-color:#444654;color:#dcce85;font-weight:bold;" name="message" class="form-control" placeholder="Ask question" 
                   >
                </InputTextArea>
            </p>
            <div class="row">
                <div class="col">
                    <div class="d-grid gap-2">
                        <button class="btn form-button" type="submit">Send</button>
                    </div>
                </div>
                <div class="col">
                    <div class="d-grid gap-2">
                        <button class="btn form-button" @onclick="Resend" type="button">Resend</button>
                    </div>
                </div>
                <div class="col">
                    <div class="d-grid gap-2">
                        <button class="btn form-button" @onclick="NewChat" type="button">Reset</button>
                    </div>
                </div>
            </div>
        </EditForm>
    </div>
</div>
hgc7kmma

hgc7kmma1#

当你在Android上的主线程中发出网络请求(或其他可能长时间运行的操作)时会抛出此错误。因此你可以创建一个新线程来读取响应AsStream。比如Thread subthread = new Thread();

注意:如果要更新Android上的UI,则需要在Main Thread上运行UI代码。

此外,您还可以尝试Task.Run(async() => {});通过线程池运行代码。它还将使代码在子线程上运行。
你可以参考github上关于NetworkOnMainThreadException when using HttpClient的问题。

相关问题