我一直在开发一个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) 我写了一个包含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) 我需要为每个单元测试都有一个登录用户,这迫使我在测试中进行异步调用(登录)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) 我变得非常大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 分钟。任何想法如何实现异步过滤,至少能够显示一些“处理..”动画来帮助用户克服这个问题?
我正在使用 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) 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)会对代码行为产生影响?
在这里使用 goto 似乎很自然。
一个项目需要读取pdf文件,pdf文件可以是以下之一。
只有使用正确的密码才能访问文件,无法预先知道文件需要哪个密码。我们必须尝试所有情况,(包括没有密码)。如果以上密码均无效,则抛出异常。
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 …
我有一些以下形式的代码:
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()等.但是我需要从一开始就引用每个任务,并且实例化任务似乎会自动启动它,这是我不想要的.这该怎么做?
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 图像时,它实际上是根据用户输入旋转的,但我松开了压缩,所以使用了上面的方法(用谷歌搜索)..现在我对此有一些疑问..
我有大量的视图模型,每个视图模型都是针对一种特定的对象类型设计的(例如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# ×9
asynchronous ×3
.net ×2
async-await ×2
task ×2
generics ×1
goto ×1
inheritance ×1
interface ×1
nunit ×1
powershell ×1
readability ×1
threadpool ×1
try-catch ×1
unit-testing ×1
winforms ×1
wpf ×1