如何解决“当前线程未与渲染器的同步上下文关联"的问题? [英] How to fix 'The current thread is not associated with the renderer's synchronization context'?

查看:87
本文介绍了如何解决“当前线程未与渲染器的同步上下文关联"的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在blazor服务器端应用程序中更改用于标题的字符串.但是我无法更新用户界面.

我尝试使用StateHasChanged(),但是没有用,所以我环顾四周,发现在

我所要做的就是调用ChangePage(某些页面标题"),它可以正常工作,除非像我提到的那样尝试刷新.

我只是想通过一个组件更改一个组件上的字符串,这听起来并不那么疯狂.如果有更好的方法来制作标题或更改其他组件中的内容,我将很乐意听到.

那么,我该怎么做才能确保m调用方法在正确的线程上? 还是有另一种更改标题的方法更有效?

提前谢谢!

解决方案

我在早上发布了第一件事,以为我没有时间去研究,并以为到了有人能够帮助我,我本来可以抽空研究一下.尽管我已经花了几天的时间来回反复.

我终于找到了这篇文章,其中解释了我试图做的就是所谓的状态容器.

他们说的是,我可以将类作为单例注入,这是我正在做的事情或作用域服务.原来我要做的就是将其更改为有范围的服务,并且效果很好!

I am trying to change change a string, being used for a title, in my blazor-server-side application. But I am having trouble getting the UI to update.

I tried using StateHasChanged(), but that didn't work so I looked around and found that on the FlightFinder Demo that was made, it has an OnChange event Action, so I am trying to implement that.

It works until I try to refresh the browser, then I am hit with this error

System.InvalidOperationException: 'The current thread is not associated with the renderer's synchronization context. Use Invoke() or InvokeAsync() to switch execution to the renderer's synchronization context when triggering rendering or modifying any state accessed during rendering.'

This is what I have:

private string _title = "TestSite";
public string Title => _title;

public event Action OnChange;

public void ChangePage(string pageName)
{
   _title = pageName;
   NotifyStateChanged();
}

private void NotifyStateChanged(int navigationType = 0)
{
   OnChange?.Invoke();
}

All I have to do is call ChangePage("some Page Title") and it works, unless like I mentioned I try to refresh.

I am just trying to change a string on one component that through another component, which doesn't sound all that crazy. If there is a better way to do titles or changing things from other components, I would love to hear about it.

So, what can I do to make sure that m invoke method is on the correct thread? Or is there a different way to change the title that would be more effective?

Thank you in advance!

解决方案

I posted this first thing in the morning thinking that I wouldn't have the time to look into and thinking that by time someone was able to help me out, I would have found the time to look into it more. Though I have spent a couple of days going back and forth on this already.

I finally found this article that explains that what I am trying to do is called a State Container.

What they said is that I could inject the class as a singleton, which is what I was doing or a scoped service. Turns out all I needed to do was change it to a scoped service and it works great!

这篇关于如何解决“当前线程未与渲染器的同步上下文关联"的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆