RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-264267

Emigrant's questions

Martin Hope
Emigrant
Asked: 2020-02-08 17:20:34 +0000 UTC

asp.net核心中长时间运行的后台进程

  • 1

我有web api。asp.net core在表单的按钮上,我启动了一个可以运行长达 5 小时的后台任务。

问题是大约1小时后后台任务被强制终止。

首先,我是这样启动后台任务的:

// POST api/analytics/run
[Route("api/[controller]/run")]
[HttpPost]
public async Task<JsonResult> RunAnalyticsAsync([FromBody] DataRequested dataRequested)
{
    await Task.Factory.StartNew(async () =>
    {
        do
        {
            //
        }
        while (report.Status == ReportStatus.Working);
        await CloudTableService.UpdateClientData(report);
    });
}

从代码中可以看出,数据必须存储在一个表中。如果后台线程已经运行了不到一个小时,那么就会发生这种情况。如果更多,则保存达不到。起初,我以为我没有正确运行后台进程。

找到文章在 ASP.NET Core 中使用托管服务的后台任务

我选择了最后一个选项:队列中的后台任务。适应您的项目。我在F5调试模式下运行。大约一个小时后,同样的事情发生了。我还注意到visual studio一个小时后在调试模式下,它(调试)结束(输出窗口,调用堆栈关闭),没有关于异常或错误的信息,web api它仍然可用。当在 Web 应用程序中刷新页面时(与 一起使用web api),有关活动后台任务的信息会消失,并且会从表中加载前一个后台任务的结果。

我将活动任务保存在这样一个类中,该类被声明为单例服务。

public class MemoryCacheService : IMemoryCacheService
{
    public IList<BaseReportRealTime> RealTimeReports { get; }

    public MemoryCacheService()
    {
        RealTimeReports = new List<BaseReportRealTime>();
    }
}

public interface IMemoryCacheService
{
    IList<BaseReportRealTime> RealTimeReports { get; }
}

可能是什么问题呢?

c#
  • 1 个回答
  • 10 Views
Martin Hope
Emigrant
Asked: 2020-01-24 23:22:21 +0000 UTC

在 asp.net core mvc 中使用 httpclient

  • 1

谁能向我解释为什么这个函数有时会返回我null:

public async Task<T> PostData<T>(string apiFunction, object data) where T : new()
{
    try
    {
        using (HttpResponseMessage response = await Client.PostAsJsonAsync(apiFunction, data))
        {
            if (response.IsSuccessStatusCode)
            {
                var jsonData = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(jsonData);
            }
            else return new T();
        }
    }
    catch (HttpRequestException)
    {
        return new T();
    }
    catch (JsonReaderException)
    {
        return new T();
    }
}

在声明为单例的服务中使用。被叫来控制。例如:

[HttpGet]
public async Task<IActionResult> Connect()
{
    ResponseServer responseServer = await _request.PostData<ResponseServer>("connection", userEntity);
    if (responseServer == null) responseServer = new ResponseServer();
}

您必须对null.

c#
  • 1 个回答
  • 10 Views
Martin Hope
Emigrant
Asked: 2020-11-25 23:58:26 +0000 UTC

如何使用 VisualState 更改 Visibility 属性

  • 0

我无法Visibility通过VisualStateManagercustom更改属性StateTrigger。尝试了不同的选择。

这是我自己UserControl:

<DataTemplate x:Key="TemplateA">
    <UserControl>
        <StackPanel Padding="5,0,0,5"
                    x:Name="StackA"
                    Orientation="Vertical"
                    Margin="10">
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup x:Name="NowState">
                    <VisualState x:Name="Now">
                        <VisualState.StateTriggers>
                            <triggers:BooleanDataTrigger
                                triggers:BooleanDataTrigger.TriggerValue="True"
                                triggers:BooleanDataTrigger.DataValue="{Binding IsRec}"/>
                        </VisualState.StateTriggers>
                        <VisualState.Setters>
                            <Setter Target="StackA.Background" Value="{StaticResource SystemControlHighlightListLowBrush}"/>
                        </VisualState.Setters>
                    </VisualState>
                    <VisualState x:Name="NotNow">
                        <VisualState.StateTriggers>
                            <triggers:BooleanDataTrigger
                                triggers:BooleanDataTrigger.TriggerValue="False"
                                triggers:BooleanDataTrigger.DataValue="{Binding IsRec}"/>
                        </VisualState.StateTriggers>
                        <VisualState.Setters>
                            <Setter Target="StackA.Background" Value="Transparent"/>
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
            <TextBlock x:Name="StatusText"
                       Text="Now watching:"
                       Style="{StaticResource BaseTitleStyle}"
                       HorizontalTextAlignment="Center"/>
            <TextBlock Text="{Binding FirstTitle}"
                       TextTrimming="CharacterEllipsis"
                       HorizontalTextAlignment="Center"
                       Style="{StaticResource TitleStyle}"/>
        </StackPanel>
    </UserControl>
</DataTemplate>

属性Background毫无疑问地发生变化。

的第一个选项Visibility也可以通过Setter任何值的文本看到IsRec:

<Setter Target="StatusText.Visibility" Value="Collapsed"/>

通过Storyboard相同的第二个选项:

 <Storyboard>
     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="StatusText" Storyboard.TargetProperty="Visibility">
         <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/>
     </ObjectAnimationUsingKeyFrames>
 </Storyboard>

目前它是通过转换器完成的,但我想知道为什么不能通过VisualStateManager.

c#
  • 1 个回答
  • 10 Views
Martin Hope
Emigrant
Asked: 2020-11-18 22:51:41 +0000 UTC

如何以编程方式更改资源字典中声明的键的值

  • 1

我在资源中声明了两个键:

<x:Double x:Key="LargerSize">20</x:Double>
<x:Double x:Key="BigSize">24</x:Double>

在这里使用:

<Style x:Key="baseTitleStyle" TargetType="TextBlock">
    <Setter Property="FontFamily" Value="/Assets/Fonts/Poppins-Regular.ttf#Poppins"/>
    <Setter Property="FontSize" Value="{StaticResource LargerSize}" />
</Style>

<Style x:Key="CaptionStyle" TargetType="TextBlock" BasedOn="{StaticResource baseTitleStyle}">
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="FontSize" Value="{StaticResource BigSize}" />
</Style>

当以这种方式以编程方式更改时:

App.Current.Resources["LargerSize"] = 16d;
App.Current.Resources["BigSize"] = 18d;

应用程序因异常而崩溃System.Exception: "Разрушительный сбой (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))"

uwp
  • 1 个回答
  • 10 Views
Martin Hope
Emigrant
Asked: 2020-06-25 22:06:29 +0000 UTC

TPL 中的信号量

  • 0

在我的程序中,只有一定数量的线程才能访问函数。有以下代码:

int totalTasksExecute = 3, currentTasksExecute = 0;
Task[] tasks = new Task[totalTasksExecute];
foreach(ObjModel obj in Objs)
{
    if (currentTasksExecute == totalTasksExecute)
    {
        Task.WaitAll(tasks);
        currentTasksExecute = 0;
    }
    Thread.Sleep(500);
    tasks[currentTasksExecute++] = Task.Factory.StartNew(() => GetWebInfo(obj));
}
Task.WaitAll(tasks);

由于它发生了好几次,我决定将它作为一个单独的类发布。在一个类中,我使用 Semaphore 来限制同时访问一个函数。

public class MultiTasks<T>
{
    private readonly Action<T> _callback;
    private readonly Semaphore semaphore;
    private readonly List<T> ts;
    private readonly AutoResetEvent[] waitHandles;

    private int Count;

    public MultiTasks(Action<T> callback, int maxRunTasks, List<T> objListForTask)
    {
        ts = objListForTask;
        _callback = callback;
        semaphore = new Semaphore(maxRunTasks, maxRunTasks);
        waitHandles = new AutoResetEvent[objListForTask.Count];
        for (int i = 0; i < waitHandles.Length; i++)
            waitHandles[i] = new AutoResetEvent(false);
    }
    public void Start(int waitMilliSeconds)
    {
        Count = 0;
        foreach(T obj in ts)
            Task.Factory.StartNew(() =>
            {
                semaphore.WaitOne();
                _callback(obj);
                waitHandles[Count].Set();
                Interlocked.Increment(ref Count);
                Thread.Sleep(waitMilliSeconds);
                semaphore.Release();
            });
        WaitHandle.WaitAll(waitHandles);
    }
}

我这样称呼:

MultiTasks<ObjModel> multiTasks = 
   new MultiTasks<ObjModel>(GetWebInfo, 3, objs.ToList());
multiTasks.Start(500);

问题是,在第一种情况下,处理时间大约需要 30 秒,在第二种情况下要长 2 倍。也许这个类没有正确实现?或者我没有正确使用信号量?

c#
  • 1 个回答
  • 10 Views
Martin Hope
Emigrant
Asked: 2020-06-14 23:19:11 +0000 UTC

IAsyncOperation<StoreProductResult> 不包含 GetAwaiter 的定义

  • 1

.net 标准 2.0 上有一个关于 Xamarin Forms 的项目。在通用项目中声明了一个接口:

public interface IIAPService
{
    Task<string> GetAppInfoAsync();
}

在 UWP 项目中实施时(取自 Microsoft 网站的示例:

public class IAPService : IIAPService
{
    private StoreContext context = null;

    public IAPService() { }

    public async Task<string> GetAppInfoAsync()
    {
        if (context == null)
        {
            context = StoreContext.GetDefault();
            // If your app is a desktop app that uses the Desktop Bridge, you
            // may need additional code to configure the StoreContext object.
            // For more info, see https://aka.ms/storecontext-for-desktop.
        }

        // Get app store product details. Because this might take several moments,   
        // display a ProgressRing during the operation.
        StoreProductResult queryResult = await context.GetStoreProductForCurrentAppAsync();

        if (queryResult.Product == null)
        {
            // The Store catalog returned an unexpected result.
            //textBlock.Text = "Something went wrong, and the product was not returned.";

            // Show additional error info if it is available.
            if (queryResult.ExtendedError != null)
            {
                //textBlock.Text += $"\nExtendedError: {queryResult.ExtendedError.Message}";
            }

            return;
        }

        // Display the price of the app.
        //textBlock.Text = $"The price of this app is: {queryResult.Product.Price.FormattedBasePrice}";
    }
}

一个错误:Ошибка CS4036 'IAsyncOperation<StoreProductResult>" не содержит определения для "GetAwaiter", и не удалось найти метод расширения "GetAwaiter", принимающий тип "IAsyncOperation<StoreProductResult>" в качестве первого аргумента (возможно, пропущена директива using для "System").

在 Google 的帮助下,我只找到了一个解决方案:使用 .net framework 4.5 而不是 4.0,但问题是我使用的是 .net standard 2.0

c#
  • 1 个回答
  • 10 Views
Martin Hope
Emigrant
Asked: 2020-02-11 23:35:33 +0000 UTC

绑定到静态索引器

  • 3

我在 XAML 中绑定静态属性时遇到问题。基于这个答案。我在我的类中定义了一个静态变量:

class Worker
{
    public static ObservableCollection<int> CountInDirections { get; set; }
    static Worker()
    {
        CountInDirections = new ObservableCollection<int>
        {
            0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
        };
    }
}

但 XAML 代码中出现以下错误:

Член "CountInDirections[6]" не распознан или недоступен.

这是 XAML 中的内容:

<Label Content="{Binding Path=(local:Worker.CountInDirections[6])}"/>

访问索引时出现错误。

怎么修?

c#
  • 2 个回答
  • 10 Views
Martin Hope
Emigrant
Asked: 2020-10-08 18:58:49 +0000 UTC

datagrid中单元格颜色的动态更新

  • 0

下午好。再次需要你的帮助。
以下代码无法正常工作:
XAML:

<DataGridTextColumn.CellStyle>
    <Style TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding Path=IsTypeCopied[0], Converter={StaticResource IntToBrushConverter}}"/>
    </Style>
</DataGridTextColumn.CellStyle>

IntToBrushConverter 类:

    class IntToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool b = (bool)value;
        if (b)
        {
            return Brushes.LightGreen;
        }
        else
        {
            return Brushes.Silver;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

还有一个实现 INotifyPropertyChanged 的​​ Worker 类

   public class Worker : INotifyPropertyChanged
{
    private bool[] _IsTypeCopied;

    public bool[] IsTypeCopied
    {
        get { return _IsTypeCopied; }
        set
        {
            _IsTypeCopied = value;
            OnPropertyChanged("IsTypeCopied");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public Worker()
    {
        IsTypeCopied = new bool[7];
    }
}

IsTypeCopied 更改发生在以下函数中:

        private void gridWorker_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        int index;
        try
        {
            index = gridWorker.CurrentCell.Column.DisplayIndex;
        }
        catch (NullReferenceException)
        {
            return;
        }

        if (index < 6) return;

        Worker SelectedWorker = (Worker)gridWorker.SelectedItem;
        if (SelectedWorker.isSelected)
            SelectedWorker.IsTypeCopied[index - 7] = true;
    }

首次将列表加载到 DataGrid 中时,单元格的颜色为银色。但是将 IsTypeCopied 从 false 更改为 true 不会着色为 LightGreen。最有趣的是,如果 IsTypeCopied 是通过以下方式声明的:

private bool _IsTypeCopied;
    public bool IsTypeCopied
    {
        get { return _IsTypeCopied; }
        set
        {
            _IsTypeCopied = value;
            OnPropertyChanged("IsTypeCopied");
        }
    }

然后此代码按预期工作,但有 7 个单元格需要着色。我想通过一个数组来做到这一点。

wpf
  • 1 个回答
  • 10 Views
Martin Hope
Emigrant
Asked: 2020-10-04 15:57:41 +0000 UTC

如何为 SortedList<double, List<int>> 集合正确实现 ICloneable 接口

  • 1

下午好。我在集合上实现 ICloneable 接口时遇到问题。声明了两个类:

public class CloneableSortedList<TKey, TValue> : SortedList<TKey, TValue> where TValue : ICloneable
{
    public SortedList<TKey, TValue> Clone()
    {
        CloneableSortedList<TKey, TValue> clone = new CloneableSortedList<TKey, TValue>();

        foreach (KeyValuePair<TKey, TValue> pair in this)
        {
            clone.Add(pair.Key, (TValue)pair.Value.Clone());
        }
        return clone;
    }
}
public class CloneableList<T> : List<T> where T : ICloneable
{
    public List<T> Clone()
    {
        CloneableList<T> clone = new CloneableList<T>();
        clone.AddRange(this);
        return clone;
    }
}

但是在声明时CloneableSortedList<double, List<int>> clonelist;,会发生错误:

类型“System.Collections.Generic.List”不能用作泛型类型或方法“CloneableSortedList”中的“TValue”类型参数。没有从“System.Collections.Generic.List”到“System.ICloneable”的隐式引用转换。

你能告诉我如何正确声明班级吗CloneableSortedList?

c#
  • 1 个回答
  • 10 Views
Martin Hope
Emigrant
Asked: 2020-08-21 17:31:17 +0000 UTC

ObservableCollection<T> 类和 IndexOf 函数

  • 3

下午好,我遇到了这样一个问题:ObservableCollection 类的 IndexOf 函数总是返回-1。这是代码:

ObservableCollection<Item> FilterMask = new ObservableCollection<Item>();
foreach(Worker w in ListWorker)
    {
        if(w.Directions.Count == 0) continue;
        Item ForFilter = new Item() { Text = w.Directions[0], IsSelected = true };
        if (FilterMask.IndexOf(ForFilter) == -1)
            FilterMask.Add(ForFilter);
    }

项目类示例:

public class Item : INotifyPropertyChanged
{
    string _Text;
    public string Text
    {
        get { return _Text; }
        set
        {
            _Text = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Text"));
        }
    }

    bool _IsSelected;
    public bool IsSelected
    {
        get { return _IsSelected; }
        set
        {
            _IsSelected = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

FilterMask出现重复,应该不是按照代码来的=)

c#
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5