小编Sri*_*vel的帖子

如何在异步方法中向UI提供反馈?

我一直在开发一个Windows表单项目,我有10个任务要做,我想在async某种程度上这样做.当用户单击按钮并且我调用async方法执行此操作时,这些任务将会出现.在我的代码中,我已经有了这些进程的参数列表.

我的问题是:

A)如何转换我的代码并行运行所有进程?(我想实现async/await)

B)如何向我的UI应用程序提供反馈?

下面的代码是我试过的:

我的按钮调用方法来启动进程

private void button1_Click(object sender, EventArgs e)
{
    // almost 15 process
    foreach (var process in Processes)
    {
        // call a async method to process
        ProcessObject(process);
    }
}
Run Code Online (Sandbox Code Playgroud)

模拟我的进程获取参数的方法

private async void ProcessObject(ProcessViewModel process)
{
    // this is my loop scope, which I need to run in parallel
    {
       // my code is here

       // increment the progress of this process
       process.Progress++;

       // feedback to UI (accessing the UI controls)
       UpdateRow(process); …
Run Code Online (Sandbox Code Playgroud)

.net c# asynchronous task winforms

8
推荐指数
2
解决办法
2019
查看次数

最高级别的继承

我写了一个包含1000个类的源文件,所有类都继承自上面的一个:

class Program
{
    static void Main(string[] args)
    {
        Class700 class700 = new Class700();            
    }
}
class Class1 { public Class1() { } }
class Class2 : Class1 { public Class2() { } }
class Class3 : Class2 { public Class3() { } }
class Class4 : Class3 { public Class4() { } }
class Class5 : Class4 { public Class5() { } }
//class ClassN : ClassN-1 { public ClassN() { } } where N = 2 to N …
Run Code Online (Sandbox Code Playgroud)

.net c# stack-overflow inheritance

6
推荐指数
1
解决办法
879
查看次数

在c#中设置异步UnitTests

我需要为每个单元测试都有一个登录用户,这迫使我在测试中进行异步调用(登录)SetUp.

我无法找到使这项工作的方法,我要么得到空指针异常,要么设置无效签名.

public async void SetUp() {}
Run Code Online (Sandbox Code Playgroud)

这使我的所有测试都失败了我的对象可能是因为我没有登录.

public async Task SetUp() {}
Run Code Online (Sandbox Code Playgroud)

使我的所有测试都被忽略,因为安装程序的签名无效.

而且我不想在每次测试中复制我的X行设置,因为它们都完全相同,而且......这就是设置的目的.

我错过了什么?这似乎是一个微不足道的问题.

这是我现在所拥有的,为了展示一些东西

CreateTicketViewModel _viewModel;

        [SetUp()]
        public async void SetUp()    //I have tried using Task instead of void
        {

            IUserService userService = Dependency.Instance.Resolve<IUserService>();
            await userService.LoginAsync(this.UserName, this.Password);

            _viewModel = Dependency.Instance.Resolve<CreateTicketViewModel>();
        }

        [TearDown()]
        public void TearDown()
        {
            _viewModel = null;  // I have tried removing this
        }

        [Test()]
        public void Initialization()
        {
            // If I put what's in SetUp here and add "async" before void,
            // …
Run Code Online (Sandbox Code Playgroud)

c# nunit unit-testing asynchronous async-await

5
推荐指数
1
解决办法
1014
查看次数

异步 CollectionViewSource 过滤?

我变得非常大ObservableCollection<MyItem>,我需要对它提供用户友好的过滤。

public static async Task RefilterViewAsync(this ItemsControl @this, Predicate<object> compareLogic)
{
    await Task.Run(
        () =>
        {
            var collectionView = CollectionViewSource.GetDefaultView(@this.ItemsSource);
            if (collectionView.CanFilter)
            {
                collectionView.Filter = compareLogic;
            }
            else throw new InvalidOperationException("Filtering not supported...");
            collectionView.Refresh();
        });
}
Run Code Online (Sandbox Code Playgroud)

..问题是上面的代码由于某些原因不起作用。在 UI 线程上进行拟合大约需要 1 分钟。任何想法如何实现异步过滤,至少能够显示一些“处理..”动画来帮助用户克服这个问题?

wpf collectionviewsource icollectionview

5
推荐指数
1
解决办法
2721
查看次数

如何在 C# 中停止 powershell 调用程序

我正在使用 C# 调用 powershell 命令,并且 powershell 命令在后台调用。我想终止后台线程。每次,我终止后台线程时,powershell仍在运行,这导致我无法再次运行该线程。有什么方法可以终止powershell执行吗?

后台线程如下:

Task.run(()=>{ while(...) {...                             
if (cancellationToken.IsCancellationRequested)
{
    cancellationToken.ThrowIfCancellationRequested();
}}}); 

Task.run(()=>{ 
    while(...) { powershell.invoke(powershellCommand);// it will execute here, I don't know how to stop. 
} })
Run Code Online (Sandbox Code Playgroud)

c# powershell

4
推荐指数
2
解决办法
3511
查看次数

为什么Thread.Sleep会影响新任务的创建?

private static void Main(string[] args)
{
    for (int i = 0; i < 1000; i++)
    {
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine("hej");
            Thread.Sleep(10000);
        });    
    }
    Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

为什么这段代码在一秒钟后不能打印1000次"hej"?为什么Thread.Sleep(10000)会对代码行为产生影响?

c# multithreading task threadpool

4
推荐指数
1
解决办法
575
查看次数

我可以/应该在 C# 中替换这个 GOTO 语句吗

在这里使用 goto 似乎很自然

一个项目需要读取pdf文件,pdf文件可以是以下之一。

  • 不受保护
  • 密码保护1
  • 受密码2保护
  • 密码保护3

只有使用正确的密码才能访问文件,无法预先知道文件需要哪个密码。我们必须尝试所有情况,(包括没有密码)。如果以上密码均无效,则抛出异常。

PdfReader GetPdfReader(string filePath)
{
    PdfReader r = null;
    int Retries = 0;
    start: try
    {
        switch (Retries)
        {
            case 0: r = new PdfReader(filePath); break;
            case 1: r = new PdfReader(filePath, password1); break;
            case 2: r = new PdfReader(filePath, password2); break;
            case 3: r = new PdfReader(filePath, password3); break;
        }
    }
    catch (BadPasswordException ex)
    {
        if (Retries == 3) throw ex;
        Retries++;
        goto start;
    }
    return r;
}
Run Code Online (Sandbox Code Playgroud)

嵌入 try/catch …

c# readability goto try-catch

4
推荐指数
1
解决办法
1689
查看次数

如何限制多个异步任务?

我有一些以下形式的代码:

static async Task DoSomething(int n) 
{
  ...
}

static void RunThreads(int totalThreads, int throttle) 
{
  var tasks = new List<Task>();
  for (var n = 0; n < totalThreads; n++)
  {
    var task = DoSomething(n);
    tasks.Add(task);
  }
  Task.WhenAll(tasks).Wait(); // all threads must complete
}
Run Code Online (Sandbox Code Playgroud)

麻烦的是,如果我没有限制线程,事情就会开始崩溃.现在,我想启动最多的throttle线程,并且仅在旧线程完成时才启动新线程.我尝试过几种方法,迄今为止没有一种方法可行.我遇到的问题包括:

  • tasks集合必须与所有的任务被完全填充,无论是主动还是等待执行,否则最后的.Wait()通话只着眼于它开始与线程.
  • 链接执行似乎需要使用Task.Run()等.但是我需要从一开始就引用每个任务,并且实例化任务似乎会自动启动它,这是我不想要的.

这该怎么做?

c# asynchronous task-parallel-library async-await

3
推荐指数
6
解决办法
4279
查看次数

图像的压缩类型

private static int GetCompressionType(Image image)
{
    // The zero-based index of the first occurrence within the entire array, if found; otherwise, –1.

    int compressionTagIndex = Array.IndexOf(image.PropertyIdList, 0x103);
    PropertyItem compressionTag = image.PropertyItems[compressionTagIndex];
    return BitConverter.ToInt16(compressionTag.Value, 0);
}
Run Code Online (Sandbox Code Playgroud)

程序员你好。我写了一个程序,我可以根据用户输入旋转图像(任何类型的图像)。担心的是当我旋转 tiff 图像时,它实际上是根据用户输入旋转的,但我松开了压缩,所以使用了上面的方法(用谷歌搜索)..现在我对此有一些疑问..

  1. 为什么是特定的0x103???
  2. 此方法是否特定于 Tiff ?
  3. 对于 JPG、JPEG 或 BMP,我是否需要查看压缩类型?

c#

2
推荐指数
1
解决办法
656
查看次数

Box C#对象作为通用接口

我有大量的视图模型,每个视图模型都是针对一种特定的对象类型设计的(例如Person,Car,等等).我想为这些添加通用功能,例如检查是否已存在包含特定对象(包含特定Car,Person等)的viewmodel的功能.我希望能够动态创建ViewModels(例如,为Car创建viewmodel,为Person创建viewmodel).所有视图模型都将具有不同的功能,命令等,因此我不能简单地使用一个全局视图模型.是否可以使用接口来解决这个问题,或者这是一个根本上有缺陷的设计模式?

当前代码:

namespace DummyNameSpace
{

    public interface IViewModel<T>
    {
        T DataModelObject { get; set; }
        string Name { get; set; }
    }

    public class SomeDataModelObject
    {
        public string SomeProperty { get; set; }
    }

    public class ViewModelInstance : IViewModel<SomeDataModelObject> //There will be various ViewModels that implement IViewModel, all with different 'T' types.
    {
        //Some properties, commands, etc.
    }

    public class TheMainViewModel //won't implement IViewModel, as this will be used to control all the various other viewmodels.
    {

        public void MethodBeingCalled(object …
Run Code Online (Sandbox Code Playgroud)

c# generics interface

2
推荐指数
1
解决办法
179
查看次数